问:
Python - Converting list of coordinates to latitude and longitude
I recently started learning programing and Python.

Now I've been trying to convert a list of coordinates x,y to latitude and longitude. I searched and found a method in python in this post: How to convert from UTM to LatLng in python or Javascript

But when I try to apply the function to a list of floats from a dataframe I get an error:" cannot convert the series to <class 'float'> ".
What could I be doing wrong?

My code:

```<code>import math

def utmToLatLng(zone, easting, northing, northernHemisphere=True):
if not northernHemisphere:
    northing = 10000000 - northing
 a = 6378137
e = 0.081819191
e1sq = 0.006739497
k0 = 0.9996

arc = northing / k0
mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))

ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))

ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0

cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32
cc = 151 * math.pow(ei, 3) / 96
cd = 1097 * math.pow(ei, 4) / 512
phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)

n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))

r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))
fact1 = n0 * math.tan(phi1) / r0

_a1 = 500000 - easting
dd0 = _a1 / (n0 * k0)
fact2 = dd0 * dd0 / 2

t0 = math.pow(math.tan(phi1), 2)
Q0 = e1sq * math.pow(math.cos(phi1), 2)
fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24

fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720

lof1 = _a1 / (n0 * k0)
lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0
lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120
_a2 = (lof1 - lof2 + lof3) / math.cos(phi1)
_a3 = _a2 * 180 / math.pi

latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi

if not northernHemisphere:
    latitude = -latitude

longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3

return (latitude, longitude)
</code>```

```<code>import pandas as pd

   df = pd.read_csv('Coord_rj.csv')
   x = df['x']
   y = df['y']
</code>```

```<code>for i in range(len(df)):
    lati,longi = utmToLatLng(23,x,y, False)
</code>```

What my data looks like:

```<code>x   y
529025.0    7422210.0
529114.0    7422343.0
545227.0    7435702.0
545582.0    7435741.0
</code>```

The error:

```<code>TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7368/1776418913.py in <module>
      1 for i in range(len(df)):
----> 2     lati,longi = utmToLatLng(23,x,y, False)
      3

~\AppData\Local\Temp/ipykernel_7368/3107957551.py in utmToLatLng(zone, easting, northing, northernHemisphere)
     20     cc = 151 * math.pow(ei, 3) / 96
     21     cd = 1097 * math.pow(ei, 4) / 512
---> 22     phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)
     23
     24     n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))

~\anaconda3\lib\site-packages\pandas\core\series.py in wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>
</code>```

答:
When you're reading in your input file you're assigning all of the first column to a variable, and all of the second column to a variable:

>>> import pandas as pd
>>> df = pd.read_csv('Coord_rj.csv')
>>> df
          x          y
0  529025.0  7422210.0
1  529114.0  7422343.0
2  545227.0  7435702.0
3  545582.0  7435741.0
>>> df['x']
0    529025.0
1    529114.0
2    545227.0
3    545582.0
Name: x, dtype: float64
>>> df['y']
0    7422210.0
1    7422343.0
2    7435702.0
3    7435741.0
Name: y, dtype: float64
```
<p>When you call your function you're passing the entire column to it for x and y, rather than just a row.</p>
<p>Try this instead:</p>
<pre class="lang-py prettyprint-override"><code>for i in range(len(df)):
    lati,longi = utmToLatLng(23, x[i], y[i], False)
</code>```

Body:
I recently started learning programing and Python.

Now I've been trying to convert a list of coordinates x,y to latitude and longitude. I searched and found a method in python in this post: How to convert from UTM to LatLng in python or Javascript

But when I try to apply the function to a list of floats from a dataframe I get an error:" cannot convert the series to <class 'float'> ".
What could I be doing wrong?

My code:

import math

def utmToLatLng(zone, easting, northing, northernHemisphere=True):
if not northernHemisphere:
    northing = 10000000 - northing
 a = 6378137
e = 0.081819191
e1sq = 0.006739497
k0 = 0.9996

arc = northing / k0
mu = arc / (a * (1 - math.pow(e, 2) / 4.0 - 3 * math.pow(e, 4) / 64.0 - 5 * math.pow(e, 6) / 256.0))

ei = (1 - math.pow((1 - e * e), (1 / 2.0))) / (1 + math.pow((1 - e * e), (1 / 2.0)))

ca = 3 * ei / 2 - 27 * math.pow(ei, 3) / 32.0

cb = 21 * math.pow(ei, 2) / 16 - 55 * math.pow(ei, 4) / 32
cc = 151 * math.pow(ei, 3) / 96
cd = 1097 * math.pow(ei, 4) / 512
phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)

n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))

r0 = a * (1 - e * e) / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (3 / 2.0))
fact1 = n0 * math.tan(phi1) / r0

_a1 = 500000 - easting
dd0 = _a1 / (n0 * k0)
fact2 = dd0 * dd0 / 2

t0 = math.pow(math.tan(phi1), 2)
Q0 = e1sq * math.pow(math.cos(phi1), 2)
fact3 = (5 + 3 * t0 + 10 * Q0 - 4 * Q0 * Q0 - 9 * e1sq) * math.pow(dd0, 4) / 24

fact4 = (61 + 90 * t0 + 298 * Q0 + 45 * t0 * t0 - 252 * e1sq - 3 * Q0 * Q0) * math.pow(dd0, 6) / 720

lof1 = _a1 / (n0 * k0)
lof2 = (1 + 2 * t0 + Q0) * math.pow(dd0, 3) / 6.0
lof3 = (5 - 2 * Q0 + 28 * t0 - 3 * math.pow(Q0, 2) + 8 * e1sq + 24 * math.pow(t0, 2)) * math.pow(dd0, 5) / 120
_a2 = (lof1 - lof2 + lof3) / math.cos(phi1)
_a3 = _a2 * 180 / math.pi

latitude = 180 * (phi1 - fact1 * (fact2 + fact3 + fact4)) / math.pi

if not northernHemisphere:
    latitude = -latitude

longitude = ((zone > 0) and (6 * zone - 183.0) or 3.0) - _a3

return (latitude, longitude)

import pandas as pd

   df = pd.read_csv('Coord_rj.csv')
   x = df['x']
   y = df['y']

for i in range(len(df)):
    lati,longi = utmToLatLng(23,x,y, False)

What my data looks like:

x   y
529025.0    7422210.0
529114.0    7422343.0
545227.0    7435702.0
545582.0    7435741.0

The error:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_7368/1776418913.py in <module>
      1 for i in range(len(df)):
----> 2     lati,longi = utmToLatLng(23,x,y, False)
      3

~\AppData\Local\Temp/ipykernel_7368/3107957551.py in utmToLatLng(zone, easting, northing, northernHemisphere)
     20     cc = 151 * math.pow(ei, 3) / 96
     21     cd = 1097 * math.pow(ei, 4) / 512
---> 22     phi1 = mu + ca * math.sin(2 * mu) + cb * math.sin(4 * mu) + cc * math.sin(6 * mu) + cd * math.sin(8 * mu)
     23
     24     n0 = a / math.pow((1 - math.pow((e * math.sin(phi1)), 2)), (1 / 2.0))

~\anaconda3\lib\site-packages\pandas\core\series.py in wrapper(self)
    183         if len(self) == 1:
    184             return converter(self.iloc[0])
--> 185         raise TypeError(f"cannot convert the series to {converter}")
    186
    187     wrapper.__name__ = f"__{converter.__name__}__"

TypeError: cannot convert the series to <class 'float'>

Body:
When you're reading in your input file you're assigning all of the first column to a variable, and all of the second column to a variable:

>>> import pandas as pd
>>> df = pd.read_csv('Coord_rj.csv')
>>> df
          x          y
0  529025.0  7422210.0
1  529114.0  7422343.0
2  545227.0  7435702.0
3  545582.0  7435741.0
>>> df['x']
0    529025.0
1    529114.0
2    545227.0
3    545582.0
Name: x, dtype: float64
>>> df['y']
0    7422210.0
1    7422343.0
2    7435702.0
3    7435741.0
Name: y, dtype: float64

When you call your function you're passing the entire column to it for x and y, rather than just a row.

Try this instead:

for i in range(len(df)):
    lati,longi = utmToLatLng(23, x[i], y[i], False)


来源: stackexchange

问:
Return nodes that have siblings that start-with substring of self
I'm trying to come up with a clean Xpath 1.0 expression in Excel's FILTERXML() function to return nodes with the following requirement:

The node must have a sibling (following) that starts with the exact same three characters of itself.

The point is to find out if there is some similarity to a certain degree in the data. Imagine the following sample data:

```<code><t>
    <s>ABCDEF</s>
    <s>GHIJKL</s>
    <s>MNOPQR</s>
    <s>GHISTU</s>
    <s>ABVWXY</s>
</t>
</code>```

From here, I'd like to return GHIJKL since it's first 3 characters, 'GHI', are found at the start of the second-to-last node.

I've been trying to piece together functions like starts-with(), substring() and count(), yet not been able to get it right. My (obviously wrong) attempt:

```<code>//s[count(following::*[starts-with(., substring(<placeholder>, 1,3))]>0]
</code>```

I'm unsure if it's possible at all and as to what to write instead of the placeholder or how to rework the query to tell the expression I'd like to take the three leftmost characters of each node and test if there are any duplicates in the following ones.

答:
Requirement (clean Xpath 1.0 expression): The node must have a sibling (following) that starts with the exact same three characters of itself.

As far as I understand your post, you want to get only node contents actually having followers that meet this requirement.

Sort of workaround might be to include abbreviation attributes a to each s node and to use the following XPath expression:

```<code>    "//*[substring(.,1,3)=following-sibling::*/@a]"
</code>```

To make this reproducible, I expanded the original xml content and added a numeric suffix to identify results easily (of course this would need a prior substitution I left aside to focus upon the main issue and to keep it short & simple).

```<code>Sub GetNodesHavingSimilarFollowers()
'a) Define wellformed xml content
    Dim content As String
    content = _
    "<t>" & _
        "<s a='ABC'>ABCDEF1</s>" & _
        "<s a='GHI'>GHIJKL2</s>" & _
        "<s a='MNO'>MNONot3</s>" & _
        "<s a='GHI'>GHINot4</s>" & _
        "<s a='ABV'>ABVNot5</s>" & _
        "<s a='ABC'>ABCPQR6</s>" & _
        "<s a='ABC'>ABCSTU7</s>" & _
        "<s a='ABC'>ABCNot8</s>" & _
    "</t>"
'~~~~~~~~~~~~~~~~~~~~~~~~~~
'b) Define XPath expression
'~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim XPth As String
    XPth = "//*[substring(.,1,3)=following-sibling::*/@a]"

'c) Execute FilterXML
    Dim x: x = Application.FilterXML(content, XPth)
    Select Case VarType(x)
        Case vbError
            Debug.Print "Error: ", x
        Case vbString
            Debug.Print x, "1 element only."
        Case Else
            Debug.Print Join(Application.Transpose(x), "|"), UBound(x) & " elements found."
End Select

End Sub

</code>```

Example output in VB Editor's immediate window

As nodes 3 and 5 are solitaires and nodes 4 and 8 (though showing the same abbreviation as other previous nodes) have no direct follower, there are only four elements left:

```<code>ABCDEF1|GHIJKL2|ABCPQR6|ABCSTU7           4 elements found.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to come up with a clean Xpath 1.0 expression in Excel's FILTERXML() function to return nodes with the following requirement:

The node must have a sibling (following) that starts with the exact same three characters of itself.

The point is to find out if there is some similarity to a certain degree in the data. Imagine the following sample data:

<t>
    <s>ABCDEF</s>
    <s>GHIJKL</s>
    <s>MNOPQR</s>
    <s>GHISTU</s>
    <s>ABVWXY</s>
</t>

From here, I'd like to return GHIJKL since it's first 3 characters, 'GHI', are found at the start of the second-to-last node.

I've been trying to piece together functions like starts-with(), substring() and count(), yet not been able to get it right. My (obviously wrong) attempt:

//s[count(following::*[starts-with(., substring(<placeholder>, 1,3))]>0]

I'm unsure if it's possible at all and as to what to write instead of the placeholder or how to rework the query to tell the expression I'd like to take the three leftmost characters of each node and test if there are any duplicates in the following ones.

Body:
Requirement (clean Xpath 1.0 expression): The node must have a sibling (following) that starts with the exact same three characters of itself.

As far as I understand your post, you want to get only node contents actually having followers that meet this requirement.

Sort of workaround might be to include abbreviation attributes a to each s node and to use the following XPath expression:

    "//*[substring(.,1,3)=following-sibling::*/@a]"

To make this reproducible, I expanded the original xml content and added a numeric suffix to identify results easily (of course this would need a prior substitution I left aside to focus upon the main issue and to keep it short & simple).

Sub GetNodesHavingSimilarFollowers()
'a) Define wellformed xml content
    Dim content As String
    content = _
    "<t>" & _
        "<s a='ABC'>ABCDEF1</s>" & _
        "<s a='GHI'>GHIJKL2</s>" & _
        "<s a='MNO'>MNONot3</s>" & _
        "<s a='GHI'>GHINot4</s>" & _
        "<s a='ABV'>ABVNot5</s>" & _
        "<s a='ABC'>ABCPQR6</s>" & _
        "<s a='ABC'>ABCSTU7</s>" & _
        "<s a='ABC'>ABCNot8</s>" & _
    "</t>"
'~~~~~~~~~~~~~~~~~~~~~~~~~~
'b) Define XPath expression
'~~~~~~~~~~~~~~~~~~~~~~~~~~
    Dim XPth As String
    XPth = "//*[substring(.,1,3)=following-sibling::*/@a]"

'c) Execute FilterXML
    Dim x: x = Application.FilterXML(content, XPth)
    Select Case VarType(x)
        Case vbError
            Debug.Print "Error: ", x
        Case vbString
            Debug.Print x, "1 element only."
        Case Else
            Debug.Print Join(Application.Transpose(x), "|"), UBound(x) & " elements found."
End Select

End Sub

Example output in VB Editor's immediate window

As nodes 3 and 5 are solitaires and nodes 4 and 8 (though showing the same abbreviation as other previous nodes) have no direct follower, there are only four elements left:

ABCDEF1|GHIJKL2|ABCPQR6|ABCSTU7           4 elements found.


问:
React play different audio files at once - working with different refs
I'm creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and  I'm not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?

This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!

```<code>import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));

    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        }
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (
    <div>
        {!isPlaying ? (
        <button type="button"
        className="play"
        onClick={() => setIsPlaying(true)}>
        <ImPlay2></ImPlay2> Play
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}>
        <ImStop></ImStop> Stop
        </button>
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>

    </div>
  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer
</code>```

答:
Here is a snippet for you/
Also do not forget to use according ids instead of idx and idx2

```<code>const AudioList = () => {
  /* here populate the array in format: array of objects
  {
    drums: mp3file,
    isPlaying: boolean,
    setIsPlaying: boolean,
    isLooping: boolean,
    setIsLooping: boolean,
    isOnMute: boolean,
    setIsOnMute: boolean,
  }[]
   */

  const [audios, setAudios] = useState([
    { isPlaying: true, isOnMute: false, isLooping: true, drums: "Your mpr" },
  ]); // use initial audios

  return (
    <div>
      <button
        onClick={() => {
          // similar to start all, mute all, you have full controll logic over all elements
          // also you could implement add new audiofile, or delete, similar logic :)
          setAudios((audios) =>
            audios.map((audio) => ({ ...audio, isPlaying: false }))
          );
        }}
      >
        Stop all
      </button>
      <div>
        {audios.map((audio, idx) => (
          <AudioPlayer
            key={idx}
            {...audio}
            setIsPlaying={(val) =>
              setAudios((audios) =>
                audios.map((audio, idx2) =>
                  idx === idx2 ? { ...audio, isPlaying: val } : audio
                )
              )
            }
            // similar for setMute and setLopping function,
            // i think you can figure it out, it is just a snippet:)
          />
        ))}
      </div>
    </div>
  );
};

const AudioPlayer = ({
  drums,
  isPlaying,
  setIsPlaying,
  isLooping,
  setIsLooping,
  isOnMute,
  setIsOnMute,
}) => {
  const audioRef = useRef(new Audio(drums));

  // also you have full controll of element inside component
  useEffect(() => {
    if (isOnMute) {
      audioRef.current.volume = 0;
    } else {
      audioRef.current.volume = 1;
    }
  }, [isOnMute]);
  useEffect(() => {
    if (isPlaying) {
      audioRef.current.play();
    } else {
      audioRef.current.pause();
      audioRef.current.load();
    }
  }, [isPlaying]);
  useEffect(() => {
    if (isLooping) {
      audioRef.current.loop = true;
    } else {
      audioRef.current.loop = false;
    }
  }, [isLooping]);
  return (
    <div>
      {!isPlaying ? (
        <button
          type="button"
          className="play"
          onClick={() => setIsPlaying(true)}
        >
          <ImPlay2></ImPlay2> Play
        </button>
      ) : (
        <button
          type="button"
          className="pause"
          onClick={() => setIsPlaying(false)}
        >
          <ImStop></ImStop> Stop
        </button>
      )}
      <Flex>
        <Switcher selected={isLooping} />
        <Text onClick={() => setIsLooping(true)}>Loop</Text>
        <Text onClick={() => setIsLooping(false)}>Unloop</Text>
      </Flex>
      <Flex>
        <Switcher selected={isOnMute} />
        <Text onClick={() => setIsOnMute(true)}>Mute</Text>
        <Text onClick={() => setIsOnMute(false)}>UnMute</Text>
      </Flex>
    </div>
  );
};
</code>```

Body:
I'm creating a small app that plays an audio file and have some functionalities (loop, stop, mute). My goal is to add some more audio files that all should be played and stopped at once (one button to control all), but each will have a mute button, and  I'm not sure what is the best practice to do so. I used useRef and thought maybe I need to set a refs array but how will I be able to start/stop them all at once, but still have the ability to control the mute separately?

This is my code so far. I guess I should split and have a different component for the audio sounds. Thanks for helping!

import React, {useState, useRef, useEffect} from 'react'
import {ImPlay2} from "react-icons/im"
import {ImStop} from "react-icons/im"
import styled from "styled-components"
import drums from '../loopfiles/DRUMS.mp3'
//import other audio files//

const AudioPlayer = () => {
    const [isPlaying, setIsPlaying] = useState(false);
    const [isLooping, setIsLooping] = useState(false);
    const [isOnMute, setIsOnMute] = useState(false);
    const audioRef = useRef(new Audio(drums));

    useEffect(() => {
        if (isOnMute) {
            audioRef.current.volume=0;
        }
        else {
            audioRef.current.volume=1;
        }
      }, [isOnMute]);
    useEffect(() => {
        if (isPlaying) {
            audioRef.current.play();
        } else {
            audioRef.current.pause();
            audioRef.current.load();
        }
      }, [isPlaying]);
      useEffect(() => {
        if (isLooping) {
            audioRef.current.loop = true;
        } else {
            audioRef.current.loop = false;
        }
      }, [isLooping]);
  return (

        {!isPlaying ? (
        <button type="button"
        className="play"
        onClick={() => setIsPlaying(true)}>
        <ImPlay2></ImPlay2> Play
        </button>
        ) : (
        <button type="button"
        className="pause"
        onClick={() => setIsPlaying(false)}>
        <ImStop></ImStop> Stop
        </button>
        )}
        <Flex>
            <Switcher selected={isLooping} />
            <Text
            onClick={() => setIsLooping(true)}>
            Loop
            </Text>
            <Text
            onClick={() => setIsLooping(false)}>
            Unloop
            </Text>
        </Flex>
        <Flex>
            <Switcher selected={isOnMute} />
            <Text
            onClick={() => setIsOnMute(true)}>
            Mute
            </Text>
            <Text
            onClick={() => setIsOnMute(false)}>
            UnMute
            </Text>
        </Flex>

  )
}
const Flex = styled.div`
  margin-top: 5px;
  display: flex;
  align-items: center;
  border-radius: 2px;
  background: grey;
  height: 20px;
  width: 120px;
  position: relative;
  margin-bottom: 5px;
`;
const Switcher = styled.div`
  background: black;
  border-radius: 2px;
  height: 20px;
  line-height: 41px;
  width: 50%;
  cursor: pointer;
  position: absolute;
  transition: 0.5s;
  -webkit-transition: 0.5s;
  -moz-transition: 0.5s;
  box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
  z-index: 1;
  left: ${({ selected }) =>
    selected === true ? "0px" : "60px"};
`;

const Text = styled.div`
  color: ${({ selected }) => (selected ? "black" : "white")};
  font-size: 13px;
  font-weight: 20;
  line-height: 4px;
  padding: 30;
  width: 50%;
  text-align: center;
  cursor: pointer;
`;
export default AudioPlayer

Body:
Here is a snippet for you/
Also do not forget to use according ids instead of idx and idx2

const AudioList = () => {
  /* here populate the array in format: array of objects
  {
    drums: mp3file,
    isPlaying: boolean,
    setIsPlaying: boolean,
    isLooping: boolean,
    setIsLooping: boolean,
    isOnMute: boolean,
    setIsOnMute: boolean,
  }[]
   */

  const [audios, setAudios] = useState([
    { isPlaying: true, isOnMute: false, isLooping: true, drums: "Your mpr" },
  ]); // use initial audios

  return (
    <div>
      <button
        onClick={() => {
          // similar to start all, mute all, you have full controll logic over all elements
          // also you could implement add new audiofile, or delete, similar logic :)
          setAudios((audios) =>
            audios.map((audio) => ({ ...audio, isPlaying: false }))
          );
        }}
      >
        Stop all
      </button>
      <div>
        {audios.map((audio, idx) => (
          <AudioPlayer
            key={idx}
            {...audio}
            setIsPlaying={(val) =>
              setAudios((audios) =>
                audios.map((audio, idx2) =>
                  idx === idx2 ? { ...audio, isPlaying: val } : audio
                )
              )
            }
            // similar for setMute and setLopping function,
            // i think you can figure it out, it is just a snippet:)
          />
        ))}
      </div>
    </div>
  );
};

const AudioPlayer = ({
  drums,
  isPlaying,
  setIsPlaying,
  isLooping,
  setIsLooping,
  isOnMute,
  setIsOnMute,
}) => {
  const audioRef = useRef(new Audio(drums));

  // also you have full controll of element inside component
  useEffect(() => {
    if (isOnMute) {
      audioRef.current.volume = 0;
    } else {
      audioRef.current.volume = 1;
    }
  }, [isOnMute]);
  useEffect(() => {
    if (isPlaying) {
      audioRef.current.play();
    } else {
      audioRef.current.pause();
      audioRef.current.load();
    }
  }, [isPlaying]);
  useEffect(() => {
    if (isLooping) {
      audioRef.current.loop = true;
    } else {
      audioRef.current.loop = false;
    }
  }, [isLooping]);
  return (
    <div>
      {!isPlaying ? (
        <button
          type="button"
          className="play"
          onClick={() => setIsPlaying(true)}
        >
          <ImPlay2></ImPlay2> Play
        </button>
      ) : (
        <button
          type="button"
          className="pause"
          onClick={() => setIsPlaying(false)}
        >
          <ImStop></ImStop> Stop
        </button>
      )}
      <Flex>
        <Switcher selected={isLooping} />
        <Text onClick={() => setIsLooping(true)}>Loop</Text>
        <Text onClick={() => setIsLooping(false)}>Unloop</Text>
      </Flex>
      <Flex>
        <Switcher selected={isOnMute} />
        <Text onClick={() => setIsOnMute(true)}>Mute</Text>
        <Text onClick={() => setIsOnMute(false)}>UnMute</Text>
      </Flex>
    </div>
  );
};


问:
How to delete an element from a list in Julia?
```<code>v = range(1e10, -1e10, step=-1e8) # velocities [cm/s]
deleteat!(v, findall(x->x==0,v))
</code>```

I want to delete the value 0 from v. Following this tutorial, I tried deleteat! but I get the error

```<code>MethodError: no method matching deleteat!(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}, ::Vector{Int64})
</code>```

What am I missing here?

答:
Notice the type that is returned by the function range.

```<code>typeof(range(1e10, -1e10, step=-1e8))
</code>```

The above yields to

```<code>StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}
</code>```

Calling the help function for the function deleteat!.

```<code>? deleteat!()
</code>```

deleteat!(a::Vector, inds)

Remove the items at the indices given by inds, and return the > modified a. Subsequent items are shifted to fill the resulting gap.

inds can be either an iterator or a collection of sorted and > unique integer indices, or a boolean vector of the same length as a with true indicating entries to delete.

We can convert the returned type of range using collect. Try the following code.

```<code>v = collect(range(1e10, -1e10, step=-1e8))
deleteat!(v,findall(x->x==0,v))
</code>```

Notice that we can shorten x->x==0 to iszero which yields to

```<code>v = collect(range(1e10, -1e10, step=-1e8))
deleteat!(v,findall(iszero,v))
</code>```

Body:
v = range(1e10, -1e10, step=-1e8) # velocities [cm/s]
deleteat!(v, findall(x->x==0,v))

I want to delete the value 0 from v. Following this tutorial, I tried deleteat! but I get the error

MethodError: no method matching deleteat!(::StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}, ::Vector{Int64})

What am I missing here?

Body:
Notice the type that is returned by the function range.

typeof(range(1e10, -1e10, step=-1e8))

The above yields to

StepRangeLen{Float64, Base.TwicePrecision{Float64}, Base.TwicePrecision{Float64}, Int64}

Calling the help function for the function deleteat!.

? deleteat!()

deleteat!(a::Vector, inds)

Remove the items at the indices given by inds, and return the > modified a. Subsequent items are shifted to fill the resulting gap.

inds can be either an iterator or a collection of sorted and > unique integer indices, or a boolean vector of the same length as a with true indicating entries to delete.

We can convert the returned type of range using collect. Try the following code.

v = collect(range(1e10, -1e10, step=-1e8))
deleteat!(v,findall(x->x==0,v))

Notice that we can shorten x->x==0 to iszero which yields to

v = collect(range(1e10, -1e10, step=-1e8))
deleteat!(v,findall(iszero,v))


问:
Flatten XML array to a single row in Snowflake
I have thousands of XML files which each have an array of key/value pairs. Like this:

<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>
```
<p>I need to be able to create a query that produces a single-row response for each XML file containing each of those values in a separated column named by the key. With MySQL, I was able to use extractvalue with XPath ('extras/extra[key="key_name_1"/value') for this, but with Snowflake I am not able to find a solution for this.</p>
<p>I have tried lateral flatten and then picking up the value from THIS array, but I haven't succeeded. It is probably something simple, but I am not able to find the solution.</p>
<h1>---Update---</h1>
<p>I could always use something like this:</p>
```XMLGET(XMLGET("xml_data", 'extras'):"$"[0], 'value'):"$"
```
<p>Unfortunately, all keys aren't always available making this useless.</p>
<p>Can it be that I have to do a UDF for this?</p>
<h1>--- Update 2 ---</h1>
<p>Got it working following way:</p>
<pre class="lang-sql prettyprint-override"><code>WITH Extra_1 AS (
    SELECT
        "id" as "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_1'
),
WITH Extra_2 AS (
    SELECT
        "id" AS "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_2'
)
SELECT
    "id",
    Extra_1."value" AS "key_name_1",
    Extra_2."value" AS "key_name_2",
FROM table
    JOIN Extra_1 ON Extra_1."id" = table."id";
    JOIN Extra_2 ON Extra_2."id" = table."id";
</code>```

Hopefully, someone has a simpler way to do this.

This is how easily it can be done in MySQL:

SELECT
    id,
    extractvalue( xml_data,'/extras/extra[key="key_name_1"]/value') AS key_name_1,
    extractvalue( xml_data,'/extras/extra[key="key_name_2"]/value') AS key_name_2
FROM table;
```

答:
If you have only 2 values you are wanting to pull you can merge Lukasz's answer with a CASE:

```<code>WITH fake_data AS (
    SELECT column1 as id,
        PARSE_XML(column2) as col_xml
    FROM VALUES
        (1, '<extras><extra><key>key_name_1</key><value>value_1</value></extra>
                     <extra><key>key_name_2</key><value>value_2</value></extra>
             </extras>'),
        (2, '<extras><extra><key>key_name_1</key><value>value_3</value></extra>
             </extras>'),
        (3, '<extras><extra><key>key_name_2</key><value>value_4</value></extra>
             </extras>')
 )
 SELECT *
    ,case
        when GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$" = 'key_name_1' then GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING
        when GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$" = 'key_name_1' then GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING
    end as key_name_1
    ,case
        when GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$" = 'key_name_2' then GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING
        when GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$" = 'key_name_2' then GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING
    end as key_name_2
FROM fake_data as t;
</code>```

which gives:

ID
COL_XML
KEY_NAME_1
KEY_NAME_2

1
        key_name_1     value_1           key_name_2     value_2
value_1
value_2

2
        key_name_1     value_3
value_3

3
        key_name_2     value_4

value_4

Body:
I have thousands of XML files which each have an array of key/value pairs. Like this:

<extras>
  <extra>
    <key>key_name_1</key>
    <value>value_1</value>
  </extra>
  <extra>
    <key>key_name_2</key>
    <value>value_2</value>
  </extra>
</extras>

I need to be able to create a query that produces a single-row response for each XML file containing each of those values in a separated column named by the key. With MySQL, I was able to use extractvalue with XPath ('extras/extra[key="key_name_1"/value') for this, but with Snowflake I am not able to find a solution for this.

I have tried lateral flatten and then picking up the value from THIS array, but I haven't succeeded. It is probably something simple, but I am not able to find the solution.

---Update---

I could always use something like this:

XMLGET(XMLGET("xml_data", 'extras'):"$"[0], 'value'):"$"

Unfortunately, all keys aren't always available making this useless.

Can it be that I have to do a UDF for this?

--- Update 2 ---

Got it working following way:

WITH Extra_1 AS (
    SELECT
        "id" as "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_1'
),
WITH Extra_2 AS (
    SELECT
        "id" AS "id",
        XMLGET(extra.value, 'value'):"$" AS "value"
    FROM table,
        LATERAL FLATTEN(XMLGET("xml_data", 'extras'):"$") extra
    WHERE XMLGET(extra.value, 'key'):"$" = 'key_name_2'
)
SELECT
    "id",
    Extra_1."value" AS "key_name_1",
    Extra_2."value" AS "key_name_2",
FROM table
    JOIN Extra_1 ON Extra_1."id" = table."id";
    JOIN Extra_2 ON Extra_2."id" = table."id";

Hopefully, someone has a simpler way to do this.

This is how easily it can be done in MySQL:

SELECT
    id,
    extractvalue( xml_data,'/extras/extra[key="key_name_1"]/value') AS key_name_1,
    extractvalue( xml_data,'/extras/extra[key="key_name_2"]/value') AS key_name_2
FROM table;

Body:
If you have only 2 values you are wanting to pull you can merge Lukasz's answer with a CASE:

WITH fake_data AS (
    SELECT column1 as id,
        PARSE_XML(column2) as col_xml
    FROM VALUES
        (1, '<extras><extra><key>key_name_1</key><value>value_1</value></extra>
                     <extra><key>key_name_2</key><value>value_2</value></extra>
             </extras>'),
        (2, '<extras><extra><key>key_name_1</key><value>value_3</value></extra>
             </extras>'),
        (3, '<extras><extra><key>key_name_2</key><value>value_4</value></extra>
             </extras>')
 )
 SELECT *
    ,case
        when GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$" = 'key_name_1' then GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING
        when GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$" = 'key_name_1' then GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING
    end as key_name_1
    ,case
        when GET(XMLGET(t.col_xml,  'extra', 0), '$')[0]:"$" = 'key_name_2' then GET(XMLGET(t.col_xml,  'extra', 0), '$')[1]:"$"::STRING
        when GET(XMLGET(t.col_xml,  'extra', 1), '$')[0]:"$" = 'key_name_2' then GET(XMLGET(t.col_xml,  'extra', 1), '$')[1]:"$"::STRING
    end as key_name_2
FROM fake_data as t;

which gives:

ID
COL_XML
KEY_NAME_1
KEY_NAME_2

1
        key_name_1     value_1           key_name_2     value_2
value_1
value_2

2
        key_name_1     value_3
value_3

3
        key_name_2     value_4

value_4


问:
Python Tkinter Frame Destroy to display new data
App works fine when first loaded. I need to update data on each frame to display what the user has changed.
I know I need to somehow destroy the frame to reload the data. Any suggestions on how to edit switch_frame to destroy to previous frame?</p>
```<code>class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand="true")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0,weight=1)

        self.frames = {}

        for F in (homepage, page2, page3):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.switch_frame("homepage")

    def switch_frame(self, frame_class):
        frame = self.frames[frame_class]
        frame.tkraise()
</code>```

答:
you can use:

your_frame_name.destroy() to destroy the frame

or

your_label_or_something_other_like_button_name.config(text='you can change text or anyting other you want to set new data

I hope this help you and feel free to ask again if you didnt understand something

Body:
App works fine when first loaded. I need to update data on each frame to display what the user has changed.
I know I need to somehow destroy the frame to reload the data. Any suggestions on how to edit switch_frame to destroy to previous frame?

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand="true")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0,weight=1)

        self.frames = {}

        for F in (homepage, page2, page3):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.switch_frame("homepage")

    def switch_frame(self, frame_class):
        frame = self.frames[frame_class]
        frame.tkraise()


答:
You need to use the position argument. I've defined a slightly different version for you, that does what you need.

```<code>ggplot(dt, aes(x=region, y=norm_diameter, group=interaction(imaging_date,region))) +
    geom_boxplot(position=position_dodge(1), aes(colour = factor(imaging_date), fill = after_scale(alpha(colour, 0.4)))) +
    geom_dotplot(binaxis='y', stackdir='center',
                 position=position_dodge(1), dotsize=0.4, aes(colour = factor(imaging_date), fill = after_scale(alpha(colour, 0.4))))
</code>```

I've basically used the same aes(...) for the geom_dotplot. Otherwise, note the stackdir='center' and position=position_dodge(1), which are available in the geom_dotplot function.

Reference used: http://www.sthda.com/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization

Title: 2 boxplots on the same vertical axis cause them to shift sideways

Body:
I have the following dataset:

structure(list(imaging_date = structure(c(19010, 19010, 19024,
19024, 19010, 19024, 19010, 19024, 19010, 19024, 19010, 19024,
19010, 19010, 19024, 19010, 19010, 19010, 19024, 19024, 19024,
19010, 19010, 19010, 19024, 19024, 19010, 19010, 19010, 19010,
19010, 19010, 19010, 19010, 19024, 19024), class = "Date"), diameter_on_mask = c(960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L, 480L, 960L, 960L, 960L, 960L, 960L, 960L, 960L, 960L,
960L, 960L, 960L, 480L, 480L, 480L, 480L, 480L, 480L, 480L, 480L,
480L, 480L), diameter_measured = c(1020L, 1040L, 1210L, 1120L,
532L, 626L, 541L, 595L, 519L, 602L, 515L, 638L, 519L, 518L, 593L,
1030L, 989L, 999L, 1120L, 1140L, 1220L, 1000L, 1010L, 1010L,
1370L, 1290L, 519L, 511L, 505L, 522L, 502L, 501L, 536L, 532L,
686L, 754L), slideno_cno_region_id = c("3_1_1", "3_1_2", "3_1_1",
"3_1_2", "3_1_3", "3_1_3", "3_1_4", "3_1_4", "3_1_5", "3_1_5",
"3_1_6", "3_1_6", "", "", "", "", "", "", "", "", "", "3_1_7",
"", "", "3_1_7", "", "", "", "", "", "", "", "", "", "", ""),
    region = c("inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "inlet", "inlet", "inlet", "inlet", "inlet",
    "inlet", "inlet", "middle", "middle", "middle", "middle",
    "middle", "middle", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet", "outlet",
    "outlet", "outlet", "outlet", "outlet", "outlet"), norm_diameter = c(1.0625,
    1.08333333333333, 1.26041666666667, 1.16666666666667, 1.10833333333333,
    1.30416666666667, 1.12708333333333, 1.23958333333333, 1.08125,
    1.25416666666667, 1.07291666666667, 1.32916666666667, 1.08125,
    1.07916666666667, 1.23541666666667, 1.07291666666667, 1.03020833333333,
    1.040625, 1.16666666666667, 1.1875, 1.27083333333333, 1.04166666666667,
    1.05208333333333, 1.05208333333333, 1.42708333333333, 1.34375,
    1.08125, 1.06458333333333, 1.05208333333333, 1.0875, 1.04583333333333,
    1.04375, 1.11666666666667, 1.10833333333333, 1.42916666666667,
    1.57083333333333)), row.names = c(NA, -36L), class = c("data.table",
"data.frame"), .internal.selfref = <pointer: 0x7fc0c100d2e0>, index = structure(integer(0), "`__imaging_date`" = c(1L,
2L, 5L, 7L, 9L, 11L, 13L, 14L, 16L, 17L, 18L, 22L, 23L, 24L,
27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 3L, 4L, 6L, 8L, 10L,
12L, 15L, 19L, 20L, 21L, 25L, 26L, 35L, 36L)))

I would like to group the data points according to .(imaging_date, region) and plot the individual data points along with the boxplots, similar to this graph:

And here's my code:

ggplot(dt, aes(x=region, y=norm_diameter, group = interaction(imaging_date,region)))+
  geom_point(aes(colour = factor(imaging_date)))+
  geom_boxplot(aes(colour = factor(imaging_date), fill = after_scale(alpha(colour, 0.4))))

However, as you can see above,

not all data points aligned vertically (some shift to right and left),

The boxplots are placed next to the data points, whereas I want them to overlap

What am I doing wrong in the above code?

Body:
You need to use the position argument. I've defined a slightly different version for you, that does what you need.

ggplot(dt, aes(x=region, y=norm_diameter, group=interaction(imaging_date,region))) +
    geom_boxplot(position=position_dodge(1), aes(colour = factor(imaging_date), fill = after_scale(alpha(colour, 0.4)))) +
    geom_dotplot(binaxis='y', stackdir='center',
                 position=position_dodge(1), dotsize=0.4, aes(colour = factor(imaging_date), fill = after_scale(alpha(colour, 0.4))))

I've basically used the same aes(...) for the geom_dotplot. Otherwise, note the stackdir='center' and position=position_dodge(1), which are available in the geom_dotplot function.

Reference used: http://www.sthda.com/english/wiki/ggplot2-box-plot-quick-start-guide-r-software-and-data-visualization


问:
How to add and remove views in a ScrollView without changing the current position of the view being shown?
I have a LinearLayout inside a ScrollView and I want to create the ilusion of endless scrolling by removing the views that are not visible and putting them as the next elements in the list (basically i do a linearlayout.removeView(viewOutOfScreen) and then linearlayout.addView(viewOutOfScreen). The problem is, every time this happens the view that is currently visible ends up in the top of the ScrollView. I tried doing a scrollView.scrollTo(0, -viewOutOfScreen.contentHeight) and it kinda works but the transition generates an horrible tearing artifact.
Also I'm not able to use RecyclerView given that the views are WebViews with very specific settings and executing js, so i nedd to reutilize/reposition them manually (cant't create more than i initially have).

答: I recommend using a nested RecyclerView because, it does exactly what you are trying to achieve manually. It recycles views which are out of the screen.


答:
I know I need to somehow destroy the frame to reload the data.

First, change the __init__ to show only the starting page. Also, you can create a dictionary to map page names to page classes.

```<code>class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.pages = {
            "homepage": homepage,
            "page2": page2,
            "page3": page3,
        }

        self.container = tk.Frame(self)
        self.container.pack(side="top", fill="both", expand="true")

        self.switch_frame("homepage")
</code>```

Next, modify switch_frame to destroy the old contents of self.container and then create a new instance of the requested page:

```<code>    def switch_frame(self, page_name):
        children = self.container.winfo_children()
        for child in children:
            child.destroy()

        frame_class = self.pages[page_name]
        frame = frame_class(self.container, controller=self)
        frame.pack(fill="both", expand=True)
</code>```

Title: Python Tkinter Frame Destroy to display new data

Body:
I know I need to somehow destroy the frame to reload the data.

First, change the __init__ to show only the starting page. Also, you can create a dictionary to map page names to page classes.

class App(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.pages = {
            "homepage": homepage,
            "page2": page2,
            "page3": page3,
        }

        self.container = tk.Frame(self)
        self.container.pack(side="top", fill="both", expand="true")

        self.switch_frame("homepage")

Next, modify switch_frame to destroy the old contents of self.container and then create a new instance of the requested page:

    def switch_frame(self, page_name):
        children = self.container.winfo_children()
        for child in children:
            child.destroy()

        frame_class = self.pages[page_name]
        frame = frame_class(self.container, controller=self)
        frame.pack(fill="both", expand=True)


问:
Is there an efficient algorithm to perform inverted full text search?
I have a limited list of thousands of keywords (of one or more words in each keyword) in a database. I want to efficiently find which of those keywords are in given input text without having to test each of those keywords one by one (full table scan). Allowing to match some misspelled words in the text would be even better but not essential. Any algorithm/article suggestions to solve this?</p>

答:
I don't know which database you are using but know that if it is Oracle you should have access to Oracle Text functionality (or you can ask your DBA to enable it). With the help of additional functions such as CONTAINS and proper usage of Oracle Text indexes you may achieve exactly what you want, even looking up "misspelled" words. This is done by combining CONTAINS with a function that computes the Levenshtein distance between two strings. In Oracle Text, this function is FUZZY.

There is a perfect example for you in this Oracle documentation.

I don't know other types of databases enough, but I was pretty sure that major vendors do have something in place for searching text. Just googling it up quickly, there is full-text search in:

Sql Server

PostgresSQL

DB2

MySQL

... and surely other DBMS

Anyway, it is a lot quicker to use built-in DBMS functions/procedures rather than creating your own custom functions or even searching with your programming language (though thousands of keywords is not that much)

Edit: After reading your question again, and Dean Harding's answer I felt I did not answer the question properly. Using Oracle Text, instead of using the CONTAINS function, you may use the MATCHES function (see Paragraph 4.1.3) which does exactly that: query a list of keywords stored in a table against some text and returning the ids of the keywords that were found. I'll copy below the example found in the documentation (with my own comments added):

```<code>create table queries (
  query_id      number,
  query_string  varchar2(80)
);

// Here we populate the table with the keywords
insert into queries values (1, 'oracle');
insert into queries values (2, 'larry or ellison');
insert into queries values (3, 'oracle and text');
insert into queries values (4, 'market share');

create index queryx on queries(query_string)
  indextype is ctxsys.ctxrule;

// This query will return the ids of the matched keywords
select query_id from queries
 where matches(query_string,
               'Oracle announced that its market share in databases
                increased over the last year.')>0
</code>```

I hope that it helps a little bit more than my first attempt.

Edit2: just to add that you don't perform a full table scan with this method since you are using a domain index.

OwnerDisplayName: Antonio Leitao

ContentLicense: CC BY-SA 3.0

Body:
I don't know which database you are using but know that if it is Oracle you should have access to Oracle Text functionality (or you can ask your DBA to enable it). With the help of additional functions such as CONTAINS and proper usage of Oracle Text indexes you may achieve exactly what you want, even looking up "misspelled" words. This is done by combining CONTAINS with a function that computes the Levenshtein distance between two strings. In Oracle Text, this function is FUZZY.

There is a perfect example for you in this Oracle documentation.

I don't know other types of databases enough, but I was pretty sure that major vendors do have something in place for searching text. Just googling it up quickly, there is full-text search in:

Sql Server

PostgresSQL

DB2

MySQL

... and surely other DBMS

Anyway, it is a lot quicker to use built-in DBMS functions/procedures rather than creating your own custom functions or even searching with your programming language (though thousands of keywords is not that much)

Edit: After reading your question again, and Dean Harding's answer I felt I did not answer the question properly. Using Oracle Text, instead of using the CONTAINS function, you may use the MATCHES function (see Paragraph 4.1.3) which does exactly that: query a list of keywords stored in a table against some text and returning the ids of the keywords that were found. I'll copy below the example found in the documentation (with my own comments added):

create table queries (
  query_id      number,
  query_string  varchar2(80)
);

// Here we populate the table with the keywords
insert into queries values (1, 'oracle');
insert into queries values (2, 'larry or ellison');
insert into queries values (3, 'oracle and text');
insert into queries values (4, 'market share');

create index queryx on queries(query_string)
  indextype is ctxsys.ctxrule;

// This query will return the ids of the matched keywords
select query_id from queries
 where matches(query_string,
               'Oracle announced that its market share in databases
                increased over the last year.')>0

I hope that it helps a little bit more than my first attempt.

Edit2: just to add that you don't perform a full table scan with this method since you are using a domain index.

OwnerDisplayName: Jalayn


问:
input in python to be only in string
I am a beginner in Python so kindly do not use complex or advanced code.

I have three if conditions to which I want certain responses, and I want my code to give only one response.

First I want the input to only answer in string not in integer or float

```<code>f = input("Please enter your name :")
</code>```

it should give an error if an integer or float is given

```<code>if type (f)== int or float :
    print("Invalid entry")
</code>```

```<code>if f=="" :
    print("Invalid input. Your name cannot be blank. ")
</code>```

I have already tried

```<code>f = str(input("Please enter your name :"))
</code>```

it is not working my code still accepts the ans in integer and string.

If I give the string input it gives me the following response:

```<code>if type (f)== int or float :
    print("Invalid entry")
</code>```

I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.

答:
input() always returns a string, so you can try these methods:

METHOD 1. Use isalpha(). It checks if all characters are alphabetical, but does not allow for spaces.

```<code>name = input('Please enter your name: ')
if name.isalpha() == False:
    print('Please enter a alphabetical name')
</code>```

To allow spaces in a name (for example, first and last name), do this:

```<code>name = input('Please enter your name: ')
nospacename = name.replace(' ','')
if nospacename.isalpha() == False:
    print('Please enter a alphabetical name')
</code>```

This does  not change the value of name, however.

METHOD 2. Try to convert it to a integer or float, and  print the message if it is possible. Otherwise, do nothing.

```<code>name = input('Please enter your name: ')
try:
    intname = int(name)
    floatname = float(name)
    print('Please enter an alphabetical name.')
except:
    pass
</code>```

METHOD 3. Go through the name, character by character, and check if it is a type int (integer) or float.

```<code>name = input('Please enter your name: ')
namelist = list(name)
invalid = 0
for i in range(len(name)):
    if type(namelist[i]) == int:
        invalid = invalid + 1
    elif type(namelist[i]) == float:
        invalid = invalid + 1
    else:
        pass

if invalid > 0:
    print('Please enter a alphabetical name.')

</code>```

Title: input in python to be only in string

Body:
I am a beginner in Python so kindly do not use complex or advanced code.

I have three if conditions to which I want certain responses, and I want my code to give only one response.

First I want the input to only answer in string not in integer or float

f = input("Please enter your name :")

it should give an error if an integer or float is given

if type (f)== int or float :
    print("Invalid entry")

if f=="" :
    print("Invalid input. Your name cannot be blank. ")

I have already tried

f = str(input("Please enter your name :"))

it is not working my code still accepts the ans in integer and string.

If I give the string input it gives me the following response:

if type (f)== int or float :
    print("Invalid entry")

I am a beginner so I might have made a lot of mistakes. Your patience would be appreciated.

Body:
input() always returns a string, so you can try these methods:

METHOD 1. Use isalpha(). It checks if all characters are alphabetical, but does not allow for spaces.

name = input('Please enter your name: ')
if name.isalpha() == False:
    print('Please enter a alphabetical name')

To allow spaces in a name (for example, first and last name), do this:

name = input('Please enter your name: ')
nospacename = name.replace(' ','')
if nospacename.isalpha() == False:
    print('Please enter a alphabetical name')

This does  not change the value of name, however.

METHOD 2. Try to convert it to a integer or float, and  print the message if it is possible. Otherwise, do nothing.

name = input('Please enter your name: ')
try:
    intname = int(name)
    floatname = float(name)
    print('Please enter an alphabetical name.')
except:
    pass

METHOD 3. Go through the name, character by character, and check if it is a type int (integer) or float.

name = input('Please enter your name: ')
namelist = list(name)
invalid = 0
for i in range(len(name)):
    if type(namelist[i]) == int:
        invalid = invalid + 1
    elif type(namelist[i]) == float:
        invalid = invalid + 1
    else:
        pass

if invalid > 0:
    print('Please enter a alphabetical name.')


问:
Count the number of punctuation symbols in a string Kotlin
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

```<code>fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }
</code>```

答:
You can make use of the built-in count function on CharSequence to count the occurrence of arbitrary characters.

val testString = "Some string containing punctuation, like !, @, #, etc."
val punctuationChars = setOf('!', '@', '#', '$', '%', '.')

val occurrences = testString.count { char -> char in punctuationChars }

println("I've counted $occurrences occurrences!")
```
<p>If you need this functionality more often, you might want to extract it into an extension function, e.g.</p>
<pre class="lang-kotlin prettyprint-override"><code>fun CharSequence.countCharacters(searchedCharacters: Set<Char>): Int =
    this.count { char -> char in searchedCharacters }

val punctuationChars = setOf('!', '@', '#', '$', '%', '.')

fun CharSequence.countPunctuationCharacters(): Int =
    this.countCharacters(punctuationChars)
</code>```

Then you can do

val occurrences = testString.countPunctuationCharacters()
```

Thanks to @CryptoFool for the example string.

Body:
I have a question how can I count the number of punctuation symbols in a string.

Here is my code snippet

fun punctuationCount(stringValue: Editable): Int {
        val trimmedStr = stringValue.trim()
        return if (trimmedStr.isEmpty()) {
            0
        } else {
           return trimmedStr.split("[a-zA-Z&&[ \t]]".toRegex()).size
        }
    }

Body:
You can make use of the built-in count function on CharSequence to count the occurrence of arbitrary characters.

val testString = "Some string containing punctuation, like !, @, #, etc."
val punctuationChars = setOf('!', '@', '#', '$', '%', '.')

val occurrences = testString.count { char -> char in punctuationChars }

println("I've counted $occurrences occurrences!")

If you need this functionality more often, you might want to extract it into an extension function, e.g.

fun CharSequence.countCharacters(searchedCharacters: Set<Char>): Int =
    this.count { char -> char in searchedCharacters }

val punctuationChars = setOf('!', '@', '#', '$', '%', '.')

fun CharSequence.countPunctuationCharacters(): Int =
    this.countCharacters(punctuationChars)

Then you can do

val occurrences = testString.countPunctuationCharacters()

Thanks to @CryptoFool for the example string.


问:
Can update packages by expo publishing (OTA updates)?
Today i want to ask anyone who has had more experience with expo updates! Since I want to install new packages via npm install .. and I was wondering if this would work properly? Or i should build app bundle and send it to stores? According to official documentation there should be no problem.

Sorry for my bad English!

答:
its fine if lib (package) has only js side ( no ios or android folder basicly but peer deps too so check theyr package.json too ! ), if it has native code you have to make new build, btw remember use release channals when u have more then 1 binary out

but there is catch even if lib is pure JS, and catch is Apple rules, OTA should be used for hotfixes only if do it for JS package update you just break rules but idk how apple will know about it :D
Source (3.3.2) - https://developer.apple.com/programs/information/Apple_Developer_Program_Information_8_12_15.pdf


问:
Angular: Swiper carousel is not working - Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts
I am trying to create a carousel in angular using swiper (https://swiperjs.com/angular).

I get this error:

Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not satisfy the constraint '(...args: any) => any'.
Type '((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ... 75 more ... | undefined' is not assignable to type '(...args: any) => any'.
Type 'undefined' is not assignable to type '(...args: any) => any'.

I have tried this:

-Uninstall and install again swiper with npm i swiper

-Uninstall swiper and install it again with npm i @types/swiper

Here is my code:

angular.json

```<code>    "styles": [
      "src/myTheme.scss",
      "src/styles.css",
      "node_modules/swiper/swiper-bundle.min.css"
    ],
    "scripts": ["node_modules/swiper/swiper-bundle.min.js"]
  },
</code>```

The shared module

```<code>import { SwiperModule } from 'swiper/angular';
  exports: [
    SwiperModule,
    other modules
  ]
</code>```

the component:

```<code>  config: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 50,
    navigation: true,
    pagination: { clickable: true },
    scrollbar: { draggable: true },
  };

//in the methods
  onSwiper([swiper]) {
    console.log(swiper);
  }
  onSlideChange() {
    console.log('slide change');
  }
</code>```

the HTLM

```<code><swiper
      [config]="config"
      (swiper)="onSwiper($event)"
      (slideChange)="onSlideChange()"
    >
  <ng-template swiperSlide>Slide 1</ng-template>
  <ng-template swiperSlide>Slide 2</ng-template>
  <ng-template swiperSlide>Slide 3</ng-template>
  <ng-template swiperSlide>Slide 4</ng-template>
  <ng-template swiperSlide>Slide 5</ng-template>
  <ng-template swiperSlide>Slide 6</ng-template>
</swiper>
</code>```

does sb have an idea of what is hapenning??
Thanks

答:
Installing swiper@7 works. But for Angular 13, an error like this might show.

```<code>Error: node_modules/swiper/angular/angular/src/public-api.d.ts:1:15 - error TS2307: Cannot find module './swiper-events' or its corresponding type declarations.

1 export * from './swiper-events';
</code>```

But this can be resolved by running a simple npm update.

Body:
I am trying to create a carousel in angular using swiper (https://swiperjs.com/angular).

I get this error:

Error: node_modules/swiper/angular/angular/src/swiper-events.d.ts:3:50 - error TS2344: Type 'SwiperEvents[Property]' does not satisfy the constraint '(...args: any) => any'.
Type '((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ((swiper: Swiper) => void) | ... 75 more ... | undefined' is not assignable to type '(...args: any) => any'.
Type 'undefined' is not assignable to type '(...args: any) => any'.

I have tried this:

-Uninstall and install again swiper with npm i swiper

-Uninstall swiper and install it again with npm i @types/swiper

Here is my code:

angular.json

    "styles": [
      "src/myTheme.scss",
      "src/styles.css",
      "node_modules/swiper/swiper-bundle.min.css"
    ],
    "scripts": ["node_modules/swiper/swiper-bundle.min.js"]
  },

The shared module

import { SwiperModule } from 'swiper/angular';
  exports: [
    SwiperModule,
    other modules
  ]

the component:

  config: SwiperOptions = {
    slidesPerView: 3,
    spaceBetween: 50,
    navigation: true,
    pagination: { clickable: true },
    scrollbar: { draggable: true },
  };

//in the methods
  onSwiper([swiper]) {
    console.log(swiper);
  }
  onSlideChange() {
    console.log('slide change');
  }

the HTLM

<swiper
      [config]="config"
      (swiper)="onSwiper($event)"
      (slideChange)="onSlideChange()"
    >
  <ng-template swiperSlide>Slide 1</ng-template>
  <ng-template swiperSlide>Slide 2</ng-template>
  <ng-template swiperSlide>Slide 3</ng-template>
  <ng-template swiperSlide>Slide 4</ng-template>
  <ng-template swiperSlide>Slide 5</ng-template>
  <ng-template swiperSlide>Slide 6</ng-template>
</swiper>

does sb have an idea of what is hapenning??
Thanks

Body:
Installing swiper@7 works. But for Angular 13, an error like this might show.

Error: node_modules/swiper/angular/angular/src/public-api.d.ts:1:15 - error TS2307: Cannot find module './swiper-events' or its corresponding type declarations.

1 export * from './swiper-events';

But this can be resolved by running a simple npm update.


问:
Create a list of values from nested dictionary Python
I have the following data structure:

```<code>listionary = [{'a': [{'id': 30, 'name': 'bob'}, {'id': 50, 'name':'mike'}]},
             {'b': [{'id': 99, 'name': 'guy'}, {'id': 77, 'name':'hal'}]}]
</code>```

and I want to create a list of the values for each 'id' key.

```<code>ie. lst = [30, 50, 99, 77]
</code>```

I know I need three iterators to traverse through the structure:

one to access the two parents dictionaries inside the array, another to access the lists of keys 'a' and 'b', and then a last to get the value of each id key in the nested child dictionaries

I tried

```<code>lst = [[x][y][y]['id'] for x, y, z in listionary]
</code>```

but I got an error of

```<code>ValueError: not enough values to unpack (expected 3, got 1)
</code>```

Is there a clean way to implement this?

答:
You can do this with 3 for loops in list comprehension:

listionary = [
    {"a": [{"id": 30, "name": "bob"}, {"id": 50, "name": "mike"}]},
    {"b": [{"id": 99, "name": "guy"}, {"id": 77, "name": "hal"}]},
]

lst = [d["id"] for d in listionary for v in d.values() for d in v]
print(lst)
```
<p>Prints:</p>
```[30, 50, 99, 77]
```

Explanation:

for d in listionary - this will iterate over all items inside list listionary ({"a":...}, {"b":...})

for v in d.values() - this will iterate over all items inside these dictionaries ([{"id:...}, {"id":...}], [...])

for d in v - this will get all dictionaries from these lists ({"id:...}, {"id":...}, ....)

d["id"] - this will get value from the key "id"

Body:
I have the following data structure:

listionary = [{'a': [{'id': 30, 'name': 'bob'}, {'id': 50, 'name':'mike'}]},
             {'b': [{'id': 99, 'name': 'guy'}, {'id': 77, 'name':'hal'}]}]

and I want to create a list of the values for each 'id' key.

ie. lst = [30, 50, 99, 77]

I know I need three iterators to traverse through the structure:

one to access the two parents dictionaries inside the array, another to access the lists of keys 'a' and 'b', and then a last to get the value of each id key in the nested child dictionaries

I tried

lst = [[x][y][y]['id'] for x, y, z in listionary]

but I got an error of

ValueError: not enough values to unpack (expected 3, got 1)

Is there a clean way to implement this?

Body:
You can do this with 3 for loops in list comprehension:

listionary = [
    {"a": [{"id": 30, "name": "bob"}, {"id": 50, "name": "mike"}]},
    {"b": [{"id": 99, "name": "guy"}, {"id": 77, "name": "hal"}]},
]

lst = [d["id"] for d in listionary for v in d.values() for d in v]
print(lst)

Prints:

[30, 50, 99, 77]

Explanation:

for d in listionary - this will iterate over all items inside list listionary ({"a":...}, {"b":...})

for v in d.values() - this will iterate over all items inside these dictionaries ([{"id:...}, {"id":...}], [...])

for d in v - this will get all dictionaries from these lists ({"id:...}, {"id":...}, ....)

d["id"] - this will get value from the key "id"


问:
Ways to do bulk import of data in Netsuite efficiently?
I am exploring ways to perform bulk import customer data to Netsuite efficiently. I figured out multiple ways like CSV import, soap APIs, rest web services, suite script, etc.

I tried all these methods and got a throughput of 1.3 requests per second by a single thread, when using a concurrency level of 4 they are giving a throughput of 4.7 requests per second.

As per this throughput, if we have to migrate millions of records say 10M then it will take around 24 days to complete this migration activity.

According to my analysis, I am able to conclude that whatever bulk import option I choose, Netsuite will give me a throughput of 1 request per second per thread (standard account concurrency limit is 5). If a customer needs to increase throughput customer have to increase premium/plus account counts.

I found the concurrency governance policy from Netsuite which says I can increase the concurrency limits based on account type and premium supports.

Netsuite also says suite script 2.x supports map-reduce but I didn't find that also relevant in this case to increase throughput without increasing concurrency limits. Though  CSV Import using map-reduce may give better results but not sure about that. But CSV Import has the limitation of 25000 lines or a 50 MB size limit per file, and CSV Import efficiency also does not get beyond the concurrency support for that account.

So my questions are :

CSV Import can go beyond the concurrency level of that particular account?

Is there any way to complete 10M records migrations in 2-5 days without worrying about the concurrency limit of the account.

Does the Concurrency limit is the controlling factor here?

Am I missing something in my analysis?

答:
I can not give exact answers to your questions, but I really think that the solution is using Map/Reduce and not use CSV import within (not sure though what did you mean by: Though CSV Import using map-reduce may give better results but not sure about that.).

By design, it is easy to make a Map/Reduce script which will read CSV file line by line and then create the records using Scripting logic. The strength of Map/Red is that there is no limit to the number of Data you can treat, and also it is, by Netsuite Design, the best tool to treat massive updates.

Also Map/Red is designed to better handle concurrent process; though it is still limited concurrency, by default, and maybe not enough for you to get the 2-5 days goal unless you by more "processors".


答:
You can use solutions like Apache Lucene or Apache Solr (Lucene based HTTP full-text service) to achieve this.

Apache Lucene provides an API to index whatever data you imagine.

Based on your needs you can choose between one or another:

Lucene: index embedded in your application. In addition, Lucene offers file-system index storage or in-memory. Moreover, one important consideration is that Lucene is not implemented in all programming languages.

Solr: Centralized index service. If you need to access to this info in a distributed way, Solr is the way to go. Also, it offers some abstraction from Lucene hard concepts, making it easy to use. Due to the use of HTTP protocol and XML to exchange information between points,  is the finest solution between heterogeneous platforms.

About the spellcheking feature, Solr includes a  spellcheck "suggestions" using a built-in component

Some tutorials/info:

Solr: Wiki is the only one resource that you need.

Lucene: In StackOverflow you can find questions about tutorials, like this

Title: Is there an efficient algorithm to perform inverted full text search?

Body: I have a limited list of thousands of keywords (of one or more words in each keyword) in a database. I want to efficiently find which of those keywords are in given input text without having to test each of those keywords one by one (full table scan). Allowing to match some misspelled words in the text would be even better but not essential. Any algorithm/article suggestions to solve this?


问:
TS: Pass Union Type To Function That Accepts Subtype
```<code>// Example Code:

type Type1 = {
  a: string;
};

type Type2 = {
  a: string;
  b: number;
};

type Type3 = {
  a: string;
  b: string;
  c: string;
  d: object;
};

type Types = Type1 | Type2 | Type3;

function getType(thing: Types) {
// ...
}

function processByType(thingsToProcess: Types) {
  if (getType(thingsToProcess) === "type1") {
    processType1(thingsToProcess);
  } else if (getType(thingsToProcess) === "type2") {
    processType2(thingsToProcess);
  } else if (getType(thingsToProcess) === "type3") {
    processType3(thingsToProcess);
  } else {
    throw Error("Unknown type");
  }
}

function processType1(t: Type1) {}
function processType2(t: Type2) {}
function processType3(t: Type3) {}
</code>```

In the above code, ts wont let me pass an object of Type to any function but processType1 since Type1 has attributes in common with the rest.

How can I change my code to make this setup work?

答:
Instead of having if (getType(thingsToProcess) === "type1") {, perform the comparison inside the function so that the function can be used as a type guard.

```<code>// example implementation
function isType<T extends Types>(thing: Types, a: string): thing is T {
    return thing.a === a;
}

function processByType(thingsToProcess: Types) {
  if (isType<Type1>(thingsToProcess, "type1")) {
    processType1(thingsToProcess);
  if (isType<Type2>(thingsToProcess, "type2")) {
    processType2(thingsToProcess);
  if (isType<Type3>(thingsToProcess, "type3")) {
    processType3(thingsToProcess);
  } else {
    throw Error("Unknown type");
  }
}
</code>```

Body:
// Example Code:

type Type1 = {
  a: string;
};

type Type2 = {
  a: string;
  b: number;
};

type Type3 = {
  a: string;
  b: string;
  c: string;
  d: object;
};

type Types = Type1 | Type2 | Type3;

function getType(thing: Types) {
// ...
}

function processByType(thingsToProcess: Types) {
  if (getType(thingsToProcess) === "type1") {
    processType1(thingsToProcess);
  } else if (getType(thingsToProcess) === "type2") {
    processType2(thingsToProcess);
  } else if (getType(thingsToProcess) === "type3") {
    processType3(thingsToProcess);
  } else {
    throw Error("Unknown type");
  }
}

function processType1(t: Type1) {}
function processType2(t: Type2) {}
function processType3(t: Type3) {}

In the above code, ts wont let me pass an object of Type to any function but processType1 since Type1 has attributes in common with the rest.

How can I change my code to make this setup work?

Body:
Instead of having if (getType(thingsToProcess) === "type1") {, perform the comparison inside the function so that the function can be used as a type guard.

// example implementation
function isType<T extends Types>(thing: Types, a: string): thing is T {
    return thing.a === a;
}

function processByType(thingsToProcess: Types) {
  if (isType<Type1>(thingsToProcess, "type1")) {
    processType1(thingsToProcess);
  if (isType<Type2>(thingsToProcess, "type2")) {
    processType2(thingsToProcess);
  if (isType<Type3>(thingsToProcess, "type3")) {
    processType3(thingsToProcess);
  } else {
    throw Error("Unknown type");
  }
}


问:
Lilypond: Instrument part transpose with several key signatures
For example, I have a very long clarinets part starts in Fis-dur and ends in G-dur written in concert pitch.
How can I apply transposition to them without causing weird key signatures at the beggining or at the end?

```<code>ClarinetI = \relative c' {\key fis \major
fis8 gis ais b cis cis cis4 |
\key g \major
g8 a b c d d d4
}
ClarinetII = \relative c' {\key fis \major
dis8 eis fis gis ais ais ais4|
\key g \major
e8 fis g a b b b4
}
\new Staff \with {instrumentName = "clarinets in concert"}<<
\partCombine \ClarinetI \ClarinetII
>>
\new Staff \with {instrumentName = "clarinets in B"}<<
\transpose bes c' \partCombine \ClarinetI \ClarinetII
>>
</code>```

I want resulting part look like this:

Generally, as I'm exporting the score from Reaper midi — I can add some Python logic into the export process, but currently I'm inside the production and need to works with the exported parts as they are.

P.S. I've tested MuseScore against my example and...

答:
As a temporary fix, I've wrapped Fis-dur part into enharmonical transpose statement. But I would like to see more reliable and complex solution.

```<code>ClarinetI = \transpose c c' { \transpose fis ges {\key fis \major
fis8 gis ais b cis' cis' cis'4 }|
\key g \major
g8 a b c' d' d' d'4
}
ClarinetII = \transpose c c' { \transpose fis ges {\key fis \major
dis8 eis fis gis ais ais ais4|}
\key g \major
e8 fis g a b b b4
}
\new Staff \with {instrumentName = "clarinets in concert"}<<
\partCombine \ClarinetI \ClarinetII
>>
\new Staff \with {instrumentName = "clarinets in B"}<<
\transpose bes c' \partCombine \ClarinetI \ClarinetII
>>
</code>```

Body:
For example, I have a very long clarinets part starts in Fis-dur and ends in G-dur written in concert pitch.
How can I apply transposition to them without causing weird key signatures at the beggining or at the end?

ClarinetI = \relative c' {\key fis \major
fis8 gis ais b cis cis cis4 |
\key g \major
g8 a b c d d d4
}
ClarinetII = \relative c' {\key fis \major
dis8 eis fis gis ais ais ais4|
\key g \major
e8 fis g a b b b4
}
\new Staff \with {instrumentName = "clarinets in concert"}<<
\partCombine \ClarinetI \ClarinetII
>>
\new Staff \with {instrumentName = "clarinets in B"}<<
\transpose bes c' \partCombine \ClarinetI \ClarinetII
>>

I want resulting part look like this:

Generally, as I'm exporting the score from Reaper midi — I can add some Python logic into the export process, but currently I'm inside the production and need to works with the exported parts as they are.

P.S. I've tested MuseScore against my example and...

Body:
As a temporary fix, I've wrapped Fis-dur part into enharmonical transpose statement. But I would like to see more reliable and complex solution.

ClarinetI = \transpose c c' { \transpose fis ges {\key fis \major
fis8 gis ais b cis' cis' cis'4 }|
\key g \major
g8 a b c' d' d' d'4
}
ClarinetII = \transpose c c' { \transpose fis ges {\key fis \major
dis8 eis fis gis ais ais ais4|}
\key g \major
e8 fis g a b b b4
}
\new Staff \with {instrumentName = "clarinets in concert"}<<
\partCombine \ClarinetI \ClarinetII
>>
\new Staff \with {instrumentName = "clarinets in B"}<<
\transpose bes c' \partCombine \ClarinetI \ClarinetII
>>


问:
Could not find column 'PredictedLabel'
I'm using ML.Net and trying to cluster some data, and the exception I'm getting is in the title: 'Could not find  column 'PredictedLabel'. But I do have this column in my prediction class!

```<code>    public class ClusterPrediction
    {
        public uint Label { get; set; }
        // Predicted label from the trainer.
        //[ColumnName("PredictedLabel")] <-- doesn't make a differnce if I have this or not
        public uint PredictedLabel { get; set; }
        public float[] Score { get; set; } = new float[0];
        public float[] Features { get; set; } = new float[0];
    }
</code>```

Here is how I setup my pipeline:

```<code>            var clusterSchema = SchemaDefinition.Create(typeof(InputCombinedClusterData));
            for (int i = 0; i < 5; i++)
            {
                var col = clusterSchema[i];
                var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
                col.ColumnType = new VectorDataViewType(itemType, InputCombinedClusterData.LOOKBACK);
            }

            var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
            var options = new KMeansTrainer.Options
            {
                // will tune this later
                NumberOfClusters = 15,
                OptimizationTolerance = 1e-9f,
                MaximumNumberOfIterations = 10000,
            };

            var fundamentalCols = new List<string> { tons of columns };

            string featuresColumnName = "Features";
            var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
                .Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"));

            foreach (var col in fundamentalCols)
            {
                pipeline.Append(mlContext.Transforms.NormalizeMinMax(col));
            }

            pipeline.Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {lots more columns}));
            pipeline.Append(mlContext.Clustering.Trainers.KMeans(options));

            // Train the model.
            var model = pipeline.Fit(trainingData);

            // test the model
            var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);

            // Run the model on test data set
            var transformedTestData = model.Transform(testData);

            // Goes BOOM here
            var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
                transformedTestData, reuseRowObject: false).ToList();
</code>```

I do have an alternate clustering trainer that DOES work, but it has far fewer columns. I'm not seeing the difference why the one above with more columns would blow up on not finding a PredictedLabel column when both trainers are using the same prediction class? Here is the one that does work for reference:

```<code>            var clusterSchema = SchemaDefinition.Create(typeof(InputPriceClusterData));
            for (int i = 0; i < 5; i++)
            {
                var col = clusterSchema[i];
                var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
                col.ColumnType = new VectorDataViewType(itemType, InputPriceClusterData.LOOKBACK);
            }

            var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
            var options = new KMeansTrainer.Options
            {
                NumberOfClusters = 15,
                OptimizationTolerance = 1e-9f,
                MaximumNumberOfIterations = 10000
            };

            // Define the trainer.
            string featuresColumnName = "Features";
            var pipeline = mlContext.Transforms
                .Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume")
                .Append(mlContext.Clustering.Trainers.KMeans(options));

            // Train the model.
            var model = pipeline.Fit(trainingData);

            // test the model
            var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);

            // Run the model on test data set.
            var transformedTestData = model.Transform(testData);

            // Convert IDataView object to a list.
            var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
                transformedTestData, reuseRowObject: false).ToList();
</code>```

For the initial broken trainer, what am I missing? Ordering of the appends?

答:
Might be a bit of a facepalm moment, but the .Append method on a pipeline doesn't do an in place append like someIList.Sort() would. I also found that I can batch up all the column pairs for normalization too. Doing it all in 1 shot resolved the issue:

```<code>            string featuresColumnName = "Features";
            var colPairs = new List<InputOutputColumnPair>();
            foreach (var col in fundamentalCols)
            {
                colPairs.Add(new InputOutputColumnPair(col, col));
            }

            var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
                .Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"))
                .Append(mlContext.Transforms.NormalizeMinMax(colPairs.ToArray()))
                .Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {boatload of columns}))
                .Append(mlContext.Clustering.Trainers.KMeans(options));
</code>```

Title: Could not find column 'PredictedLabel'

Body:
I'm using ML.Net and trying to cluster some data, and the exception I'm getting is in the title: 'Could not find  column 'PredictedLabel'. But I do have this column in my prediction class!

    public class ClusterPrediction
    {
        public uint Label { get; set; }
        // Predicted label from the trainer.
        //[ColumnName("PredictedLabel")] <-- doesn't make a differnce if I have this or not
        public uint PredictedLabel { get; set; }
        public float[] Score { get; set; } = new float[0];
        public float[] Features { get; set; } = new float[0];
    }

Here is how I setup my pipeline:

            var clusterSchema = SchemaDefinition.Create(typeof(InputCombinedClusterData));
            for (int i = 0; i < 5; i++)
            {
                var col = clusterSchema[i];
                var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
                col.ColumnType = new VectorDataViewType(itemType, InputCombinedClusterData.LOOKBACK);
            }

            var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
            var options = new KMeansTrainer.Options
            {
                // will tune this later
                NumberOfClusters = 15,
                OptimizationTolerance = 1e-9f,
                MaximumNumberOfIterations = 10000,
            };

            var fundamentalCols = new List<string> { tons of columns };

            string featuresColumnName = "Features";
            var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
                .Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"));

            foreach (var col in fundamentalCols)
            {
                pipeline.Append(mlContext.Transforms.NormalizeMinMax(col));
            }

            pipeline.Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {lots more columns}));
            pipeline.Append(mlContext.Clustering.Trainers.KMeans(options));

            // Train the model.
            var model = pipeline.Fit(trainingData);

            // test the model
            var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);

            // Run the model on test data set
            var transformedTestData = model.Transform(testData);

            // Goes BOOM here
            var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
                transformedTestData, reuseRowObject: false).ToList();

I do have an alternate clustering trainer that DOES work, but it has far fewer columns. I'm not seeing the difference why the one above with more columns would blow up on not finding a PredictedLabel column when both trainers are using the same prediction class? Here is the one that does work for reference:

            var clusterSchema = SchemaDefinition.Create(typeof(InputPriceClusterData));
            for (int i = 0; i < 5; i++)
            {
                var col = clusterSchema[i];
                var itemType = ((VectorDataViewType)col.ColumnType).ItemType;
                col.ColumnType = new VectorDataViewType(itemType, InputPriceClusterData.LOOKBACK);
            }

            var trainingData = mlContext.Data.LoadFromEnumerable(data.TrainingData);
            var options = new KMeansTrainer.Options
            {
                NumberOfClusters = 15,
                OptimizationTolerance = 1e-9f,
                MaximumNumberOfIterations = 10000
            };

            // Define the trainer.
            string featuresColumnName = "Features";
            var pipeline = mlContext.Transforms
                .Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume")
                .Append(mlContext.Clustering.Trainers.KMeans(options));

            // Train the model.
            var model = pipeline.Fit(trainingData);

            // test the model
            var testData = mlContext.Data.LoadFromEnumerable(data.TestingData);

            // Run the model on test data set.
            var transformedTestData = model.Transform(testData);

            // Convert IDataView object to a list.
            var predictions = mlContext.Data.CreateEnumerable<ClusterPrediction>(
                transformedTestData, reuseRowObject: false).ToList();

For the initial broken trainer, what am I missing? Ordering of the appends?

Body:
Might be a bit of a facepalm moment, but the .Append method on a pipeline doesn't do an in place append like someIList.Sort() would. I also found that I can batch up all the column pairs for normalization too. Doing it all in 1 shot resolved the issue:

            string featuresColumnName = "Features";
            var colPairs = new List<InputOutputColumnPair>();
            foreach (var col in fundamentalCols)
            {
                colPairs.Add(new InputOutputColumnPair(col, col));
            }

            var pipeline = mlContext.Transforms.Categorical.OneHotEncoding("Sector")
                .Append(mlContext.Transforms.Categorical.OneHotEncoding("Industry"))
                .Append(mlContext.Transforms.NormalizeMinMax(colPairs.ToArray()))
                .Append(mlContext.Transforms.Concatenate(featuresColumnName, "Open", "High", "Low", "Close", "Volume", "Sector", "Industry", {boatload of columns}))
                .Append(mlContext.Clustering.Trainers.KMeans(options));


问:
How to display an unordered list into a JSX
 element in a React Form using class component
I'd like to write an unordered list compiled from a form's input values into a
 when I click on the Submit button. It's a controlled form in a class based component. Unfortunately I haven't found out how I can achieve it without hooks.

```<code>export default  class  App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            name: "",
            email: "",
            message: "",
            demo: "",
          };

        this.changeHandler = this.changeHandler.bind(this);
        this.submitFormHandler = this.submitFormHandler.bind(this);
    }

    changeHandler = (e)  => {
        this.setState = {
            name: e.target.value,
            email: e.target.value,
            message: e.target.value,
            demo: `
      <li>${this.state.name}</li>
      <li>${this.state.email}</li>
      <li>${this.state.message}</li> `
      };
    this.setState(this.setState)
  };

    submitFormHandler = (e)  => {
    e.preventDefault();
    // I guess the solution will be here somehow
    };

    render() {
    return (
        <form  onSubmit={this.submitFormHandler} >

            <label htmlFor="name">Name:</label>    <br/>
            <input id="name" type="text" value={this.state.name} onChange={this.changeHandler} />
            <br/>
            <label htmlFor="mail">E-mail:</label>    <br/>
            <input id="mail" type="email" value={this.state.email} onChange={this.changeHandler} />
            <br/>
            <label htmlFor="msg">Message:</label>    <br/>
            <textarea id="msg" type="email" value={this.state.message} onChange={this.changeHandler} />

            <h4>Values of the inputs:</h4>
            <ul id="demo">
                {this.state.demo}  {/* the list would be here! */}
            </ul>
            <button type="submit">Submit</button>

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

答:
To show something when it is submitted I would make a isSubmitted flag. Also you controlled inputs were not working. When inputs ids are corresponding with names in state we can easier handle them in onChange handler function. Also when it is submitted we can prevent user from updating data in changeHandler with early return. So I fixed it in code below:

// import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: '',
      email: '',
      message: '',
      isSubmitted: false,
    };

    this.changeHandler = this.changeHandler.bind(this);
    this.submitFormHandler = this.submitFormHandler.bind(this);
  }

  changeHandler = ({ target }) => {
    if (this.state.isSubmitted) return;

    this.setState({ [target.id]: target.value });
  };

  submitFormHandler = (e) => {
    e.preventDefault();
    this.setState({ isSubmitted: true });
  };

  render() {
    return (

        <form onSubmit={this.submitFormHandler}>
          Name:

          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={this.changeHandler}
          />

          E-mail:

          <input
            id="email"
            type="email"
            value={this.state.email}
            onChange={this.changeHandler}
          />

          Message:

          <textarea
            id="message"
            type="email"
            value={this.state.message}
            onChange={this.changeHandler}
          />

          <button type="submit">Submit</button>
        </form>
        {this.state.isSubmitted && (
          <React.Fragment>

Values of the inputs:

{this.state.name}

{this.state.email}

{this.state.message}

          </React.Fragment>
        )}

    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div></code>```

Title: How to display an unordered list into a JSX <ul> element in a React Form using class component

Body:
I'd like to write an unordered list compiled from a form's input values into a
 when I click on the Submit button. It's a controlled form in a class based component. Unfortunately I haven't found out how I can achieve it without hooks.

export default  class  App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            name: "",
            email: "",
            message: "",
            demo: "",
          };

        this.changeHandler = this.changeHandler.bind(this);
        this.submitFormHandler = this.submitFormHandler.bind(this);
    }

    changeHandler = (e)  => {
        this.setState = {
            name: e.target.value,
            email: e.target.value,
            message: e.target.value,
            demo: `

${this.state.name}

${this.state.email}

${this.state.message}
 `
      };
    this.setState(this.setState)
  };

    submitFormHandler = (e)  => {
    e.preventDefault();
    // I guess the solution will be here somehow
    };

    render() {
    return (
        <form  onSubmit={this.submitFormHandler} >

            Name:

            <input id="name" type="text" value={this.state.name} onChange={this.changeHandler} />

            E-mail:

            <input id="mail" type="email" value={this.state.email} onChange={this.changeHandler} />

            Message:

            <textarea id="msg" type="email" value={this.state.message} onChange={this.changeHandler} />

Values of the inputs:

                {this.state.demo}  {/* the list would be here! */}

            <button type="submit">Submit</button>

        </form>
        );  }
};

Body:
To show something when it is submitted I would make a isSubmitted flag. Also you controlled inputs were not working. When inputs ids are corresponding with names in state we can easier handle them in onChange handler function. Also when it is submitted we can prevent user from updating data in changeHandler with early return. So I fixed it in code below:

// import React from 'react';

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      name: '',
      email: '',
      message: '',
      isSubmitted: false,
    };

    this.changeHandler = this.changeHandler.bind(this);
    this.submitFormHandler = this.submitFormHandler.bind(this);
  }

  changeHandler = ({ target }) => {
    if (this.state.isSubmitted) return;

    this.setState({ [target.id]: target.value });
  };

  submitFormHandler = (e) => {
    e.preventDefault();
    this.setState({ isSubmitted: true });
  };

  render() {
    return (
      <div>
        <form onSubmit={this.submitFormHandler}>
          <label htmlFor="name">Name:</label> <br />
          <input
            id="name"
            type="text"
            value={this.state.name}
            onChange={this.changeHandler}
          />
          <br />
          <label htmlFor="email">E-mail:</label> <br />
          <input
            id="email"
            type="email"
            value={this.state.email}
            onChange={this.changeHandler}
          />
          <br />
          <label htmlFor="message">Message:</label> <br />
          <textarea
            id="message"
            type="email"
            value={this.state.message}
            onChange={this.changeHandler}
          />
          <br />
          <button type="submit">Submit</button>
        </form>
        {this.state.isSubmitted && (
          <React.Fragment>
            <h4>Values of the inputs:</h4>
            <ul>
              <li>{this.state.name}</li>
              <li>{this.state.email}</li>
              <li>{this.state.message}</li>
            </ul>
          </React.Fragment>
        )}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>