问:
How to create line between react native elements (view/touchableopacity/button) to draw family tree
I'm trying to develop React Native mobile app to draw a family tree

Any suggestion on how to draw line between the family member to create the tree, the element is touchableopacity.
I have try using react-native-svg, but I cannot get the screen coordinate of the touchableopacity.

here's the code

```<code>class FamilyTreeScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: '',
            isLoading: false,
            memberData: null,
            parentData: null,
            childData: null,
            siblingData: null,
            name: '',
            city: '',
            memberId: 0,
            age: 0
        };
    }

    componentDidMount(){
        this.getMemberData();
    }

    handleLoading = boolean => {
        this.setState({ isLoading: boolean })
    }

    async handleRTO(){
        Alert.alert('Connection Problem','Check your internet connection and try again.');
    }

    async fetchAccountData(){
        if (this.props.navigation.state.params)
            await this.setState({
                userId: this.props.navigation.getParam('memberId', 0),
            });
        else
            await this.setState({
                userId: Number(await AsyncStorage.getItem('userId')),
            });
        // console.log(this.state.userId);
    }

    async getMemberData(){
        await this.fetchAccountData();

        this.handleLoading(true);
        var req = await fetch(base_url + 'Relationship/get_relationship/' + this.state.userId, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHTTPREQUEST',
            },
        })
        .then(function(response){
            // console.log(response);
            return response.json();
        })
        .then(function(parsedJson){
            // console.log('get trah: '+JSON.stringify(parsedJson));
            if (parsedJson.status){
                return parsedJson.data;
            }
            else{
                return null;
            }
        })
        .catch(error => {
            this.handleRTO();
            console.error(error);
        });

        if (req){
            await this.setState({
                memberData: req.member,
                parentData: req.parent,
                childData: req.child,
                siblingData: req.sibling
            });
        }
        this.handleLoading(false);
    }

    renderMember(){
        if (this.state.memberData)
            return (
                <TouchableOpacity onPress={() => this.setState({
                        name: this.state.memberData[0].first_name + " " + this.state.memberData[0].middle_name + " " + this.state.memberData[0].last_name,
                        city: this.state.memberData[0].city,
                        memberId: this.state.memberData[0].member_id,
                        age: this.state.memberData[0].umur,
                    })}>
                    <View style={defaultStyles.familyTreeProfile}>
                        <Image source={this.state.memberData[0].pp ? {uri: member_img_path + this.state.memberData[0].pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                        <Text style={[textStyles.regular14, colorStyles.blackText, defaultStyles.familyTreeText]}>{this.state.memberData[0].first_name} {this.state.memberData[0].middle_name} {this.state.memberData[0].last_name}</Text>
                    </View>
                </TouchableOpacity>
            );
        else
            return null;
    }

    renderParent(){
        var memberList = [];
        if (this.state.parentData){
            this.state.parentData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.parent_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                            name: item.first_name + " " + item.middle_name + " " + item.last_name,
                            city: item.city,
                            memberId: item.parent_id,
                            age: item.umur
                        })}>
                        <View style={defaultStyles.familyTreeProfile}
                          ref={(ref) => { this.marker = ref }}
                          onLayout={({nativeEvent}) => {
                              console.log("render parent");
                            if (this.marker) {
                              this.marker.measure((x, y, width, height, pageX, pageY) => {
                                        console.log(x, y, width, height, pageX, pageY);
                               })
                            }
                          }}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>
                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderSibling(){
        var memberList = [];
        if (this.state.siblingData){
            this.state.siblingData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.person_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                        name: item.first_name + " " + item.middle_name + " " + item.last_name,
                        city: item.city,
                        memberId: item.person_id,
                        age: item.umur
                    })}>
                        <View style={defaultStyles.familyTreeProfile}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>
                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderChild(){
        var memberList = [];
        if (this.state.childData){
            this.state.childData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.person_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                        name: item.first_name + " " + item.middle_name + " " + item.last_name,
                        city: item.city,
                        memberId: item.person_id,
                        age: item.umur
                    })}>
                        <View style={defaultStyles.familyTreeProfile}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>

                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderUmur(){
        if (this.state.memberId)
            return (
                <Text>{this.state.age} old</Text>
            );
        else
            return null;
    }

    renderButton(){
        if (this.state.memberId)
            return (
                <View style={defaultStyles.btnContainer2}>
                    <Button style={[defaultStyles.trahMembershipButton]} onPress={() => this.props.navigation.navigate('PublicProfile', {
                        memberId: this.state.memberId
                    })}>
                        <Icon
                            active
                            type="FontAwesome"
                            name="user"
                            style={[{fontSize: 25}, colorStyles.blackText]}
                        />
                    </Button>
                    <Text> </Text>
                    <Button style={[defaultStyles.trahMembershipButton]} onPress={() => this.props.navigation.push('FamilyTree', {
                        memberId: this.state.memberId
                    })}>
                        <Image source={familytree_navbar} style={defaultStyles.trahMembershipImage} />
                    </Button>
                </View>
            );
        else
            return null;
    }

    render() {
        if (this.state.isLoading){
            return (
                <View style={defaultStyles.loading}>
                    <ActivityIndicator
                        size="large"
                    />
                </View>
            );
        }
        else{
            return (
                <Container style={[defaultStyles.container, colorStyles.bg]}>
                    <Header style={[colorStyles.yellow, defaultStyles.registerHeader]}>
                        <Left>
                            <Button transparent onPress={() => this.props.navigation.goBack()}>
                                <Icon
                                    type="FontAwesome"
                                    name="angle-left"
                                    style={[colorStyles.blackText]}
                                />
                            </Button>
                        </Left>
                        <Body style={defaultStyles.headerContent}>
                            <Title style={[colorStyles.blackText, textStyles.bold18]}>FAMILY TREE</Title>
                        </Body>
                    </Header>
                    <Content contentContainerStyle={defaultStyles.contentContainer}>
                        <ScrollView contentContainerStyle={{flexGrow: 1}} horizontal={true}>
                            <PinchZoomView>
                                <View style={defaultStyles.familyTreeContainer}>
                                    {this.renderParent()}
                                </View>
                                <View style={defaultStyles.familyTreeContainer}
                      ref={(ref) => { this.marker = ref }}
                      onLayout={({nativeEvent}) => {
                        console.log("render member");
                        if (this.marker) {
                          this.marker.measure((x, y, width, height, pageX, pageY) => {
                                    console.log(x, y, width, height, pageX, pageY);
                           })
                        }
                      }}>
                                    {this.renderMember()}
                                    {this.renderSibling()}
                                </View>
                                <View style={defaultStyles.familyTreeContainer}>
                                    {this.renderChild()}
                                </View>
                            </PinchZoomView>
                        </ScrollView>
                        <View style={defaultStyles.bottom}>
                            <Text>{this.state.name}</Text>
                            <Text>{this.state.city}</Text>
                            {this.renderUmur()}
                            {this.renderButton()}
                        </View>
                    </Content>
                    {Navbar(this.props.navigation, 'familytree')}
                </Container>
            );
        }
    }
}
export default FamilyTreeScreen;
</code>```

If you have any suggestion, please let me know, Thank you

答:
If your concern is just a line, you can easily achieve it by using the css below. Just give it to your component which needs to have line;</p>
```<code>line: {
      borderBottomWidth: 1, // it can be border left or border right width
      borderColor: "#0000", // or any color,
      borderWidth: 120, // Should be number. 120 is just an example
    },
</code>```

Body:
I'm trying to develop React Native mobile app to draw a family tree

Any suggestion on how to draw line between the family member to create the tree, the element is touchableopacity.
I have try using react-native-svg, but I cannot get the screen coordinate of the touchableopacity.

here's the code

class FamilyTreeScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            userId: '',
            isLoading: false,
            memberData: null,
            parentData: null,
            childData: null,
            siblingData: null,
            name: '',
            city: '',
            memberId: 0,
            age: 0
        };
    }

    componentDidMount(){
        this.getMemberData();
    }

    handleLoading = boolean => {
        this.setState({ isLoading: boolean })
    }

    async handleRTO(){
        Alert.alert('Connection Problem','Check your internet connection and try again.');
    }

    async fetchAccountData(){
        if (this.props.navigation.state.params)
            await this.setState({
                userId: this.props.navigation.getParam('memberId', 0),
            });
        else
            await this.setState({
                userId: Number(await AsyncStorage.getItem('userId')),
            });
        // console.log(this.state.userId);
    }

    async getMemberData(){
        await this.fetchAccountData();

        this.handleLoading(true);
        var req = await fetch(base_url + 'Relationship/get_relationship/' + this.state.userId, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHTTPREQUEST',
            },
        })
        .then(function(response){
            // console.log(response);
            return response.json();
        })
        .then(function(parsedJson){
            // console.log('get trah: '+JSON.stringify(parsedJson));
            if (parsedJson.status){
                return parsedJson.data;
            }
            else{
                return null;
            }
        })
        .catch(error => {
            this.handleRTO();
            console.error(error);
        });

        if (req){
            await this.setState({
                memberData: req.member,
                parentData: req.parent,
                childData: req.child,
                siblingData: req.sibling
            });
        }
        this.handleLoading(false);
    }

    renderMember(){
        if (this.state.memberData)
            return (
                <TouchableOpacity onPress={() => this.setState({
                        name: this.state.memberData[0].first_name + " " + this.state.memberData[0].middle_name + " " + this.state.memberData[0].last_name,
                        city: this.state.memberData[0].city,
                        memberId: this.state.memberData[0].member_id,
                        age: this.state.memberData[0].umur,
                    })}>
                    <View style={defaultStyles.familyTreeProfile}>
                        <Image source={this.state.memberData[0].pp ? {uri: member_img_path + this.state.memberData[0].pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                        <Text style={[textStyles.regular14, colorStyles.blackText, defaultStyles.familyTreeText]}>{this.state.memberData[0].first_name} {this.state.memberData[0].middle_name} {this.state.memberData[0].last_name}</Text>
                    </View>
                </TouchableOpacity>
            );
        else
            return null;
    }

    renderParent(){
        var memberList = [];
        if (this.state.parentData){
            this.state.parentData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.parent_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                            name: item.first_name + " " + item.middle_name + " " + item.last_name,
                            city: item.city,
                            memberId: item.parent_id,
                            age: item.umur
                        })}>
                        <View style={defaultStyles.familyTreeProfile}
                          ref={(ref) => { this.marker = ref }}
                          onLayout={({nativeEvent}) => {
                              console.log("render parent");
                            if (this.marker) {
                              this.marker.measure((x, y, width, height, pageX, pageY) => {
                                        console.log(x, y, width, height, pageX, pageY);
                               })
                            }
                          }}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>
                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderSibling(){
        var memberList = [];
        if (this.state.siblingData){
            this.state.siblingData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.person_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                        name: item.first_name + " " + item.middle_name + " " + item.last_name,
                        city: item.city,
                        memberId: item.person_id,
                        age: item.umur
                    })}>
                        <View style={defaultStyles.familyTreeProfile}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>
                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderChild(){
        var memberList = [];
        if (this.state.childData){
            this.state.childData.map((item, idx) => {
                memberList.push(
                    // <TouchableOpacity onPress={() => this.props.navigation.navigate('PublicProfile', {
                    //     memberId: item.person_id
                    // })}>
                    <TouchableOpacity onPress={() => this.setState({
                        name: item.first_name + " " + item.middle_name + " " + item.last_name,
                        city: item.city,
                        memberId: item.person_id,
                        age: item.umur
                    })}>
                        <View style={defaultStyles.familyTreeProfile}>
                            <Image source={item.pp ? {uri: member_img_path + item.pp} : pp_home} style={defaultStyles.familyTreePhoto} />
                            <Text style={[textStyles.regular14, colorStyles.blackText]}>{item.first_name} {item.middle_name} {item.last_name}</Text>

                        </View>
                    </TouchableOpacity>
                );
            });
        }
        return memberList;
    }

    renderUmur(){
        if (this.state.memberId)
            return (
                <Text>{this.state.age} old</Text>
            );
        else
            return null;
    }

    renderButton(){
        if (this.state.memberId)
            return (
                <View style={defaultStyles.btnContainer2}>
                    <Button style={[defaultStyles.trahMembershipButton]} onPress={() => this.props.navigation.navigate('PublicProfile', {
                        memberId: this.state.memberId
                    })}>
                        <Icon
                            active
                            type="FontAwesome"
                            name="user"
                            style={[{fontSize: 25}, colorStyles.blackText]}
                        />
                    </Button>
                    <Text> </Text>
                    <Button style={[defaultStyles.trahMembershipButton]} onPress={() => this.props.navigation.push('FamilyTree', {
                        memberId: this.state.memberId
                    })}>
                        <Image source={familytree_navbar} style={defaultStyles.trahMembershipImage} />
                    </Button>
                </View>
            );
        else
            return null;
    }

    render() {
        if (this.state.isLoading){
            return (
                <View style={defaultStyles.loading}>
                    <ActivityIndicator
                        size="large"
                    />
                </View>
            );
        }
        else{
            return (
                <Container style={[defaultStyles.container, colorStyles.bg]}>

                        <Left>
                            <Button transparent onPress={() => this.props.navigation.goBack()}>
                                <Icon
                                    type="FontAwesome"
                                    name="angle-left"
                                    style={[colorStyles.blackText]}
                                />
                            </Button>
                        </Left>

                            <Title style={[colorStyles.blackText, textStyles.bold18]}>FAMILY TREE</Title>

                    <Content contentContainerStyle={defaultStyles.contentContainer}>
                        <ScrollView contentContainerStyle={{flexGrow: 1}} horizontal={true}>
                            <PinchZoomView>
                                <View style={defaultStyles.familyTreeContainer}>
                                    {this.renderParent()}
                                </View>
                                <View style={defaultStyles.familyTreeContainer}
                      ref={(ref) => { this.marker = ref }}
                      onLayout={({nativeEvent}) => {
                        console.log("render member");
                        if (this.marker) {
                          this.marker.measure((x, y, width, height, pageX, pageY) => {
                                    console.log(x, y, width, height, pageX, pageY);
                           })
                        }
                      }}>
                                    {this.renderMember()}
                                    {this.renderSibling()}
                                </View>
                                <View style={defaultStyles.familyTreeContainer}>
                                    {this.renderChild()}
                                </View>
                            </PinchZoomView>
                        </ScrollView>
                        <View style={defaultStyles.bottom}>
                            <Text>{this.state.name}</Text>
                            <Text>{this.state.city}</Text>
                            {this.renderUmur()}
                            {this.renderButton()}
                        </View>
                    </Content>
                    {Navbar(this.props.navigation, 'familytree')}
                </Container>
            );
        }
    }
}
export default FamilyTreeScreen;

If you have any suggestion, please let me know, Thank you

Body:
If your concern is just a line, you can easily achieve it by using the css below. Just give it to your component which needs to have line;

line: {
      borderBottomWidth: 1, // it can be border left or border right width
      borderColor: "#0000", // or any color,
      borderWidth: 120, // Should be number. 120 is just an example
    },


来源: stackexchange

问:
spring-boot TCP server: wait for `empty line` before answering a `multi-line` request
I would like to write a custom check_policy_service (http://www.postfix.org/SMTPD_POLICY_README.html) for postfix with spring-boot.

Short: postfix sends multiple lines like:

```<code>foo=bar
me=you
year=123
[empty line]
</code>```

The empty line indicates, that the request is complete, now the spring-boot app should handle the data and return something like action=ok

Problem:
In my current setup the app tries to handle line 1 foo=bar immediately and does not wait until the [empty line] is sent. How can I make the app wait for the empty line?

Current setup:
spring-boot 2.6.3

@Configuration
class TcpServerConfig {
//    @Value("\${tcp.server.port}")
    private val port = 6676
    @Bean
    fun serverConnectionFactory(): AbstractServerConnectionFactory {
        val serverConnectionFactory = TcpNioServerConnectionFactory(port)
        serverConnectionFactory.setUsingDirectBuffers(true)
        serverConnectionFactory.isSingleUse = false // reuse socket
        return serverConnectionFactory
    }
    @Bean
    fun inboundChannel(): MessageChannel {
        return DirectChannel()
    }

    @Bean
    fun inboundGateway(
        serverConnectionFactory: AbstractServerConnectionFactory,
        inboundChannel: MessageChannel
    ): TcpInboundGateway {
        val tcpInboundGateway = TcpInboundGateway()
        tcpInboundGateway.setConnectionFactory(serverConnectionFactory)
        tcpInboundGateway.setRequestChannel(inboundChannel)
        return tcpInboundGateway
    }
}
```
<pre class="lang-kotlin prettyprint-override"><code>@MessageEndpoint
class TcpServerEndpoint {

    @ServiceActivator(inputChannel = "inboundChannel")
    fun process(message: ByteArray): ByteArray {

        // I would need to have `message` contain every line until empty line - not a single line
        println(String(message))

        // TODO handle message accordingly
        return "action=ok\n".toByteArray()
    }
}
</code>```

I am not sure where to hook in. Maybe DirectChannel needs to be something else?

I wrote a quick non spring-boot implementation which works, so basically I need the spring-boot-ified version of:

fun main(args: Array<String>) {
    val server = ServerSocket(9999)
    println("Server is running on port ${server.localPort}")

    while (true) {
        val client = server.accept()
        println("Client connected: ${client.inetAddress.hostAddress}")

        // Run client in it's own thread.
        thread { ClientHandler(client).run() }
    }

}

class ClientHandler(client: Socket) {
    private val client: Socket = client
    private val reader: BufferedReader = BufferedReader(InputStreamReader(client.getInputStream()))
    private val writer: PrintWriter = PrintWriter(client.getOutputStream(), true)
    private var running: Boolean = false

    fun run() {
        running = true
        while (running) {
            try {
                do {
                    val line = reader.readLine() ?: break
                    // TODO collect all lines in a list and handle
                } while (line.isNotEmpty())

                write("action=ok")

            } catch (ex: Exception) {
                // TODO: Implement exception handling
                ex.printStackTrace()
                shutdown()
            } finally {

            }
        }
    }

    private fun write(message: String) {
        writer.write((message + "\n\n"))
        writer.flush()
    }
    private fun shutdown() {
        running = false
        client.close()
        println("${client.inetAddress.hostAddress} closed the connection")
    }
}
```

The magic part is read all lines until line is empty and then handle the request(s)

答:
You need to set the Deserializer so that Spring knows when to release the read content (so far) to the handler as described in the docs.

In your case, you should write a custom deserializer implementing the interface org.springframework.core.serializer.Deserializer that releases the content to the handler as soon as it has detected two newlines in a row. Make it return a List<String> with the lines sent by Postfix:

```<code>class DoubleNewLineDeserializer: Deserializer<List<String>> {

    companion object {
        const val UNIX_NEWLINE = "\n\n"
        const val WINDOWS_NEWLINE = "\r\n\r\n"
        val CRLFRegex = Regex("[\r\n]+")
    }

    override fun deserialize(inputStream: InputStream): List<String> {
        val builder = StringBuilder()
        while(!builder.endsWith(UNIX_NEWLINE) && !builder.endsWith(WINDOWS_NEWLINE))
            builder.append(inputStream.read().toChar())
        return builder.toString().split(CRLFRegex).filter { it.isNotEmpty() }
    }

}
</code>```

This deserializer reads input until it finds a double new line (here either \n\n or \r\n\r\n, you can modify this as you want) at which point it removes the message delimiter and then returns the message as a list of lines.

Finally, set your new deserializer on the ServerConnectionFactory:

```<code>serverConnectionFactory.deserializer = DoubleNewLineDeserializer()
</code>```

Input to TCP socket:

```<code>foo=bar
me=you
year=123
[empty line]
[empty line]
</code>```

Input to handler:

```<code>[foo=bar, me=you, year=123]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to write a custom check_policy_service (http://www.postfix.org/SMTPD_POLICY_README.html) for postfix with spring-boot.

Short: postfix sends multiple lines like:

foo=bar
me=you
year=123
[empty line]

The empty line indicates, that the request is complete, now the spring-boot app should handle the data and return something like action=ok

Problem:
In my current setup the app tries to handle line 1 foo=bar immediately and does not wait until the [empty line] is sent. How can I make the app wait for the empty line?

Current setup:
spring-boot 2.6.3

@Configuration
class TcpServerConfig {
//    @Value("\${tcp.server.port}")
    private val port = 6676
    @Bean
    fun serverConnectionFactory(): AbstractServerConnectionFactory {
        val serverConnectionFactory = TcpNioServerConnectionFactory(port)
        serverConnectionFactory.setUsingDirectBuffers(true)
        serverConnectionFactory.isSingleUse = false // reuse socket
        return serverConnectionFactory
    }
    @Bean
    fun inboundChannel(): MessageChannel {
        return DirectChannel()
    }

    @Bean
    fun inboundGateway(
        serverConnectionFactory: AbstractServerConnectionFactory,
        inboundChannel: MessageChannel
    ): TcpInboundGateway {
        val tcpInboundGateway = TcpInboundGateway()
        tcpInboundGateway.setConnectionFactory(serverConnectionFactory)
        tcpInboundGateway.setRequestChannel(inboundChannel)
        return tcpInboundGateway
    }
}

@MessageEndpoint
class TcpServerEndpoint {

    @ServiceActivator(inputChannel = "inboundChannel")
    fun process(message: ByteArray): ByteArray {

        // I would need to have `message` contain every line until empty line - not a single line
        println(String(message))

        // TODO handle message accordingly
        return "action=ok\n".toByteArray()
    }
}

I am not sure where to hook in. Maybe DirectChannel needs to be something else?

I wrote a quick non spring-boot implementation which works, so basically I need the spring-boot-ified version of:

fun main(args: Array<String>) {
    val server = ServerSocket(9999)
    println("Server is running on port ${server.localPort}")

    while (true) {
        val client = server.accept()
        println("Client connected: ${client.inetAddress.hostAddress}")

        // Run client in it's own thread.
        thread { ClientHandler(client).run() }
    }

}

class ClientHandler(client: Socket) {
    private val client: Socket = client
    private val reader: BufferedReader = BufferedReader(InputStreamReader(client.getInputStream()))
    private val writer: PrintWriter = PrintWriter(client.getOutputStream(), true)
    private var running: Boolean = false

    fun run() {
        running = true
        while (running) {
            try {
                do {
                    val line = reader.readLine() ?: break
                    // TODO collect all lines in a list and handle
                } while (line.isNotEmpty())

                write("action=ok")

            } catch (ex: Exception) {
                // TODO: Implement exception handling
                ex.printStackTrace()
                shutdown()
            } finally {

            }
        }
    }

    private fun write(message: String) {
        writer.write((message + "\n\n"))
        writer.flush()
    }
    private fun shutdown() {
        running = false
        client.close()
        println("${client.inetAddress.hostAddress} closed the connection")
    }
}

The magic part is read all lines until line is empty and then handle the request(s)

Body:
You need to set the Deserializer so that Spring knows when to release the read content (so far) to the handler as described in the docs.

In your case, you should write a custom deserializer implementing the interface org.springframework.core.serializer.Deserializer that releases the content to the handler as soon as it has detected two newlines in a row. Make it return a List<String> with the lines sent by Postfix:

class DoubleNewLineDeserializer: Deserializer<List<String>> {

    companion object {
        const val UNIX_NEWLINE = "\n\n"
        const val WINDOWS_NEWLINE = "\r\n\r\n"
        val CRLFRegex = Regex("[\r\n]+")
    }

    override fun deserialize(inputStream: InputStream): List<String> {
        val builder = StringBuilder()
        while(!builder.endsWith(UNIX_NEWLINE) && !builder.endsWith(WINDOWS_NEWLINE))
            builder.append(inputStream.read().toChar())
        return builder.toString().split(CRLFRegex).filter { it.isNotEmpty() }
    }

}

This deserializer reads input until it finds a double new line (here either \n\n or \r\n\r\n, you can modify this as you want) at which point it removes the message delimiter and then returns the message as a list of lines.

Finally, set your new deserializer on the ServerConnectionFactory:

serverConnectionFactory.deserializer = DoubleNewLineDeserializer()

Input to TCP socket:

foo=bar
me=you
year=123
[empty line]
[empty line]

Input to handler:

[foo=bar, me=you, year=123]


问:
I'm getting an error that says my random_number variable doesn't exist. Any advice on what I should do to create it?
I'm working on homework and I need to take random observations from a data set. I am trying to create the random data set based on my teacher's coding instructions but I keep getting an error saying my random_number variable does not exist. I have posted an image of my code. Do I need to create the variable or make a proc sort for it?
Code

Here are the error logs:

434  proc print data= random_sample (obs=100);
435      var id country year random_number pr cl;
ERROR: Variable RANDOM_NUMBER not found.
436  run;

NOTE: The SAS System stopped processing this step because of errors.
NOTE: PROCEDURE PRINT used (Total process time):
real time           0.00 seconds
cpu time            0.00 seconds

答:
If your goal is to select a random sample then one way to do this is creating a new column with a random number between [0, 1], then sort, then select the first N rows.

```<code>data want;
  set have;
  random_number = rand(“uniform”);
run;
proc sort data=want;
  by random_number;
run;
proc print data=want(obs=100);
run;
</code>```

In case you need something different, please clarify your question.

Body:
If your goal is to select a random sample then one way to do this is creating a new column with a random number between [0, 1], then sort, then select the first N rows.

data want;
  set have;
  random_number = rand(“uniform”);
run;
proc sort data=want;
  by random_number;
run;
proc print data=want(obs=100);
run;

In case you need something different, please clarify your question.


问:
Can I create administrator user for ceph?
I can create basic user and it's subusers. Is it possible to create administrator user in ceph who can access all objects and buckets from all users?</p>

答:
The answer is: Yes

And I know it's a tricky question. Because creating admin user is still not very straightforward.

The Ceph Storage Cluster provides an administrative API that enables users to execute administrative functions via the REST API. By default, users do NOT have access to this API. To enable a user to exercise administrative functionality, provide the user with administrative capabilities.

To add administrative capabilities to a user, execute the following:

radosgw-admin caps add --uid={uid} --caps={caps}

You can add read, write or all capabilities to users, buckets, metadata and usage (utilization). For example:

--caps="[users|buckets|metadata|usage|zone|amz-cache|info|bilog|mdlog|datalog|user-policy|oidc-provider|roles|ratelimit]=[*|read|write|read, write]"

For example:

radosgw-admin caps add --uid=johndoe --caps="users=*;buckets=*"

To remove administrative capabilities from a user, execute the following:

radosgw-admin caps rm --uid=johndoe --caps={caps}


问:
Trying to find repeated names in a database
Database at hand

I have this database at hand and i want to mess around with it trying to learn what i can.
I'm trying to see if names in the "EmployeeName" column has the names that have been around for at least 3 years so i can see how their pay increased or decreased in those years.

df3.duplicated(subset=['EmployeeName'])

i have tried this but issue with this is that the first resulst will always come out False since they didnt get "repeated" yet so it counts that as a False for their first instance but sees that the name got repeated later down the database then says True but some of the names really has no duplicates.

So how can i find out who really gets repeated and how can i take out the non repeated ones.
I'm new to this,just got this database from Kaggle and trying to see which jobs got better or worse throught the years then try and visualize it.

Thank You.

答:
You probably want something like this.</p>
```<code>SELECT * FROM YourTable WHERE COUNT(EmployeeName) > 1 ORDER BY Year;
</code>```

Body:
You probably want something like this.

SELECT * FROM YourTable WHERE COUNT(EmployeeName) > 1 ORDER BY Year;


问:
why the classification models use top5 accuracy in evaluation metrics?
I was checking the evaluation metrics in Resnet and Mobilenet and I was wondering why top5 accuracy is used for evaluation metrics? The highest probability will be selected and top1 accuracy is the best for these applications.</p>

答:
You can for example train different models (or same models but with different training methods or having different weights in general), and pick the top 5 (for example) performing models which give the best top-5 accuracy. Then (assuming you have enough resources and computing power) you can rank the top 5 predictions of each model and apply some formula to rank the best prediction overall.
For example, when testing on some sample, all of the 5 models are ranking the correct classification as second, but the first prediction is different in each of them, so according to your ranking algorithm the correct prediction should have better rank than all of the other predictions since it ranked second in all of the models.</p>


问:
How to show RSS as pop-up?
On my website users can post comments on a document. Now I want to send an RSS feed to the webmasters when a comment is posted. I want the webmaster to be notified by a small pop-up in the right corner of the page. So this is what's happening:

User adds comment

system checks if webmaster is logged in

if webmaster is logged in; show pop-up in right corner with the title of the comment in it.

How to accomplish this?

答:
Setup a javascript timer to call a webservice periodically (every 5 seconds?) if the user is a webmaster. This webservice can determine if a new comment has been added since the last time it was checked. The webservice returns nothing if no new comment or some information about the comment if there is a new one.

If the webservice returns a comment, put that information into a div tag that you have created on your page and make it visible. If you are sure the webmaster is using a modern browser, you can use position:fixed to put this div tag in the upper right corner. If not, you will have to use some javascript to accomplish this.

OwnerDisplayName: Martijn

Title: How to show RSS as pop-up?

OwnerDisplayName: Keltex

ContentLicense: CC BY-SA 2.5


问:
Entity Framework with multiple data sources
Is it possible to have an EDM that retrieves data from two data sources at the same time ? Say, it retrieves 3 tables from an SQL Server database and some other data from a binary file ?</p>

答:
short answer: no

You could link database servers within your edmx main database and write views or stored procedures that access the data from the linked server tables.

ContentLicense: CC BY-SA 3.0


问:
React UseContext with useReducer re-renders the whole app even after splitting
I am struggling to prevent my whole app getting re-rendered.I have even tried to split the context and memoize components but nothing helps me.
I have already read Use context Github issue this thread and a lot of other articles describing the right implementation but with no result.
I am using websockets to retrieve bitcoin value every second and it causes the whole app re-render on every second.

This is the App.tsx

```<code><AppProvider>
  <ThemeProvider theme={theme}>
    <GlobalStyles />
    <BrowserRouter>
      <div className="App">
        <AppRoot isBusy={!ready || !isConnected} />
      </div>
    </BrowserRouter>
  </ThemeProvider>
</AppProvider>
</code>```

This is the main context

```<code>import React, { createContext, useReducer, Dispatch } from 'react';

import { BTCReducerActions, BTCData, BTCPayload, btcReducer } from '../reducers/btc';
import { CommonReducerActions, CommonData, CommonPayload, commonReducer } from '../reducers/common';
import { UserReducerActions, UserData, UserPayload, userReducer } from '../reducers/user';

interface InitialStateType {
  user: UserData;
  btc: BTCData;
  common: CommonData;
}

const initialState: InitialStateType = {
  btc: {} as BTCData,
  common: {},
  user: {} as UserData,
};

export type ActionType = (
  BTCReducerActions |
  CommonReducerActions |
  UserReducerActions |
);
type MainReducer = (state: InitialStateType, action: ActionType) => InitialStateType;

const AppContext = createContext<{
  state: InitialStateType;
  dispatch: Dispatch<ActionType>;
}>({
  state: initialState,
  dispatch: () => null,
});

const mainReducer: MainReducer = ({ btc, common, user}, action) => ({
  btc: btcReducer<BTCPayload>(btc, action as BTCReducerActions),
  user: userReducer<UserPayload>(user, action as UserReducerActions),
  common: commonReducer<CommonPayload>(common, action as CommonReducerActions),
});

const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export { AppProvider, AppContext };
</code>```

And this is the root.tsx

```<code>export const AppRoot = memo(({ isBusy }: Record<'isBusy', boolean>) => {
  const {
    dispatch,
    state: {
      common: { isMobile, soundSettings: { state, volume } },
      user: { token },
    },
  } = useContext(AppContext);

  const history = useHistory();
  const location = useLocation();

  useEffect(() => {
    if (!isBusy) {
      SocketManager.socketEmitter('query', {
        header: { action: 'main::getInitialData' },
      }, ({ token, user: { id } }) => dispatch({ type: UserActionTypes.UpdateUserData, payload: { token, id } }));
    }
  }, [isBusy]);

  return (
    <AppRootStyled className="fb horizontal">
        <Content>
          <AppHeader />
          <div className="fb main-content">
            <Switch>
              <Route exact strict path={GAME_SCREEN} component={Roulette} />
              <Route exact strict path={STATISTICS_SCREEN} component={Activity} />
              <Route exact strict path={BET_HISTORY_SCREEN} render={props => <BetHistory roundHistory={roundHistory} {...props} />} />
              <Route exact strict path={USER_BETS_SCREEN} component={MyBets} />
            </Switch>
          </div>
        </Content>
        {location.pathname !== GAME_SCREEN && (
          <div className="go-home">
            <div className="fb horizontal aCenter jCenter">
              <Icon name="round-back-circled" onClick={() => history.push(GAME_SCREEN)} />
            </div>
          </div>
        )}
      </AppRootStyled>
  );
});
</code>```

Somewhere in the app I am using socket to get the btc data

```<code>useEffect(() => {
    SocketManager.connectChannel('main::BTCData', (data) => {
      dispatch({ type: BTCActionTypes.SetBTCData, payload: data });
    });
  }, []);
</code>```

I have already tried to create a separate context by splitting the main state so the btc data has its own slice of the state, but again the Route components re-render every second.Also other components that use the context are re-rendering every second.
This is the context splitting implementation

```<code>const AppContext = {/ ** \}

const BtcContext = createContext<{btc: BTCData}>({ btc: {} as BTCData });

const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      <BtcContext.Provider value={{btc}}>
        {children}
      </BtcContext.Provider>
    </AppContext.Provider>
  );
};
</code>```

I know I am doing something wrong.I am using context as a state management service for the first time.Before I was using only redux and haven't faced this kind of problem.
I am already on it a few days and I need to solve the problem until tomorrow morning.
I have a lot of tables and other heavy components that shouldn't re-render so often.

UPDATED

I have tried this 2 options.
OPTION 1

```<code><AppProvider>
  <BtcProvider>
    <ThemeProvider theme={theme}>
      <GlobalStyles />
      <BrowserRouter>
        <div className="App">
          <AppRoot isBusy={!ready || !isConnected} />
        </div>
      </BrowserRouter>
    </ThemeProvider>
  </BtcProvider>
</AppProvider>

const AppProvider: React.FC = ({ children }) => {
  const [{ btc, ...mainStateData }, dispatch] = useReducer(mainReducer, initialState);

  const mainState = useMemo(() => ({
    state: mainStateData,
    dispatch,
  }), [mainStateData]);

  return (
    <AppContext.Provider value={mainState}>
      {children}
    </AppContext.Provider>
  );
};

const BtcProvider: React.FC = ({ children }) => {
  const [{ btc }, dispatch] = useReducer(mainReducer, initialState);

  const btcData = useMemo(() => ({
    btc,
    dispatch,
  }), [btc]);

  return (
    <BtcContext.Provider value={btcData}>
      {children}
    </BtcContext.Provider>
  );
};

export { AppProvider, BtcProvider, AppContext, BtcContext };
</code>```

And OPTION 2

```<code>const AppProvider: React.FC = ({ children }) => {
  const [{ btc, ...mainStateData }, dispatch] = useReducer(mainReducer, initialState);

  const mainState = useMemo(() => ({
    state: mainStateData,
    dispatch,
  }), [mainStateData]);

  const btcData = useMemo(() => ({
    btc,
    dispatch,
  }), [btc]);

  return (
    <AppContext.Provider value={mainState}>
      <BtcContext.Provider value={btcData}>
        {children}
      </BtcContext.Provider>

    </AppContext.Provider>
  );
};

 <AppProvider>
  <ThemeProvider theme={theme}>
    <GlobalStyles />
    <BrowserRouter>
      <div className="App">
        <AppRoot isBusy={!ready || !isConnected} />
      </div>
    </BrowserRouter>
  </ThemeProvider>
</code>```

The result is the same.The case is that the btc data is being changed every second and I need it to provide a lot of components, but to re-render only the components where I consume the data.

答:
```<code><AppContext.Provider value={{ state, dispatch }}>
</code>```

Every time AppProvider renders, this code creates a new object { state, dispatch }. It may have the same contents as the previous object, but it's a different object, so react is forced to rerender any component that consumes this context. Similarly, you're making a brand new object for the BtcContext.Provider.

When providing an object, you need to make sure to memoize that object so it only changes when necessary:

```<code>const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  const appValue = useMemo(() => {
    return { state, dispatch };
  }, [state]);

  const btcValue = useMemo(() => {
    return { btc };
  }, [btc]);

  return (
    <AppContext.Provider value={appValue}>
      <BtcContext.Provider value={btcValue}>
        {children}
      </BtcContext.Provider>
    </AppContext.Provider>
  );
};
</code>```

Body:
I am struggling to prevent my whole app getting re-rendered.I have even tried to split the context and memoize components but nothing helps me.
I have already read Use context Github issue this thread and a lot of other articles describing the right implementation but with no result.
I am using websockets to retrieve bitcoin value every second and it causes the whole app re-render on every second.

This is the App.tsx

<AppProvider>
  <ThemeProvider theme={theme}>
    <GlobalStyles />
    <BrowserRouter>

        <AppRoot isBusy={!ready || !isConnected} />

    </BrowserRouter>
  </ThemeProvider>
</AppProvider>

This is the main context

import React, { createContext, useReducer, Dispatch } from 'react';

import { BTCReducerActions, BTCData, BTCPayload, btcReducer } from '../reducers/btc';
import { CommonReducerActions, CommonData, CommonPayload, commonReducer } from '../reducers/common';
import { UserReducerActions, UserData, UserPayload, userReducer } from '../reducers/user';

interface InitialStateType {
  user: UserData;
  btc: BTCData;
  common: CommonData;
}

const initialState: InitialStateType = {
  btc: {} as BTCData,
  common: {},
  user: {} as UserData,
};

export type ActionType = (
  BTCReducerActions |
  CommonReducerActions |
  UserReducerActions |
);
type MainReducer = (state: InitialStateType, action: ActionType) => InitialStateType;

const AppContext = createContext<{
  state: InitialStateType;
  dispatch: Dispatch<ActionType>;
}>({
  state: initialState,
  dispatch: () => null,
});

const mainReducer: MainReducer = ({ btc, common, user}, action) => ({
  btc: btcReducer<BTCPayload>(btc, action as BTCReducerActions),
  user: userReducer<UserPayload>(user, action as UserReducerActions),
  common: commonReducer<CommonPayload>(common, action as CommonReducerActions),
});

const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      {children}
    </AppContext.Provider>
  );
};

export { AppProvider, AppContext };

And this is the root.tsx

export const AppRoot = memo(({ isBusy }: Record<'isBusy', boolean>) => {
  const {
    dispatch,
    state: {
      common: { isMobile, soundSettings: { state, volume } },
      user: { token },
    },
  } = useContext(AppContext);

  const history = useHistory();
  const location = useLocation();

  useEffect(() => {
    if (!isBusy) {
      SocketManager.socketEmitter('query', {
        header: { action: 'main::getInitialData' },
      }, ({ token, user: { id } }) => dispatch({ type: UserActionTypes.UpdateUserData, payload: { token, id } }));
    }
  }, [isBusy]);

  return (
    <AppRootStyled className="fb horizontal">
        <Content>
          <AppHeader />

            <Switch>
              <Route exact strict path={GAME_SCREEN} component={Roulette} />
              <Route exact strict path={STATISTICS_SCREEN} component={Activity} />
              <Route exact strict path={BET_HISTORY_SCREEN} render={props => <BetHistory roundHistory={roundHistory} {...props} />} />
              <Route exact strict path={USER_BETS_SCREEN} component={MyBets} />
            </Switch>

        </Content>
        {location.pathname !== GAME_SCREEN && (

              <Icon name="round-back-circled" onClick={() => history.push(GAME_SCREEN)} />

        )}
      </AppRootStyled>
  );
});

Somewhere in the app I am using socket to get the btc data

useEffect(() => {
    SocketManager.connectChannel('main::BTCData', (data) => {
      dispatch({ type: BTCActionTypes.SetBTCData, payload: data });
    });
  }, []);

I have already tried to create a separate context by splitting the main state so the btc data has its own slice of the state, but again the Route components re-render every second.Also other components that use the context are re-rendering every second.
This is the context splitting implementation

const AppContext = {/ ** \}

const BtcContext = createContext<{btc: BTCData}>({ btc: {} as BTCData });

const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  return (
    <AppContext.Provider value={{ state, dispatch }}>
      <BtcContext.Provider value={{btc}}>
        {children}
      </BtcContext.Provider>
    </AppContext.Provider>
  );
};

I know I am doing something wrong.I am using context as a state management service for the first time.Before I was using only redux and haven't faced this kind of problem.
I am already on it a few days and I need to solve the problem until tomorrow morning.
I have a lot of tables and other heavy components that shouldn't re-render so often.

UPDATED

I have tried this 2 options.
OPTION 1

<AppProvider>
  <BtcProvider>
    <ThemeProvider theme={theme}>
      <GlobalStyles />
      <BrowserRouter>

          <AppRoot isBusy={!ready || !isConnected} />

      </BrowserRouter>
    </ThemeProvider>
  </BtcProvider>
</AppProvider>

const AppProvider: React.FC = ({ children }) => {
  const [{ btc, ...mainStateData }, dispatch] = useReducer(mainReducer, initialState);

  const mainState = useMemo(() => ({
    state: mainStateData,
    dispatch,
  }), [mainStateData]);

  return (
    <AppContext.Provider value={mainState}>
      {children}
    </AppContext.Provider>
  );
};

const BtcProvider: React.FC = ({ children }) => {
  const [{ btc }, dispatch] = useReducer(mainReducer, initialState);

  const btcData = useMemo(() => ({
    btc,
    dispatch,
  }), [btc]);

  return (
    <BtcContext.Provider value={btcData}>
      {children}
    </BtcContext.Provider>
  );
};

export { AppProvider, BtcProvider, AppContext, BtcContext };

And OPTION 2

const AppProvider: React.FC = ({ children }) => {
  const [{ btc, ...mainStateData }, dispatch] = useReducer(mainReducer, initialState);

  const mainState = useMemo(() => ({
    state: mainStateData,
    dispatch,
  }), [mainStateData]);

  const btcData = useMemo(() => ({
    btc,
    dispatch,
  }), [btc]);

  return (
    <AppContext.Provider value={mainState}>
      <BtcContext.Provider value={btcData}>
        {children}
      </BtcContext.Provider>

    </AppContext.Provider>
  );
};

 <AppProvider>
  <ThemeProvider theme={theme}>
    <GlobalStyles />
    <BrowserRouter>

        <AppRoot isBusy={!ready || !isConnected} />

    </BrowserRouter>
  </ThemeProvider>

The result is the same.The case is that the btc data is being changed every second and I need it to provide a lot of components, but to re-render only the components where I consume the data.

Body:
<AppContext.Provider value={{ state, dispatch }}>

Every time AppProvider renders, this code creates a new object { state, dispatch }. It may have the same contents as the previous object, but it's a different object, so react is forced to rerender any component that consumes this context. Similarly, you're making a brand new object for the BtcContext.Provider.

When providing an object, you need to make sure to memoize that object so it only changes when necessary:

const AppProvider: React.FC = ({ children }) => {
  const [state, dispatch] = useReducer(mainReducer, initialState);

  const appValue = useMemo(() => {
    return { state, dispatch };
  }, [state]);

  const btcValue = useMemo(() => {
    return { btc };
  }, [btc]);

  return (
    <AppContext.Provider value={appValue}>
      <BtcContext.Provider value={btcValue}>
        {children}
      </BtcContext.Provider>
    </AppContext.Provider>
  );
};


问:
ext.kotlin_version = <'latest version'> error on Flutter
I am trying to place advertising in my flutter app, this is proving to be almost more complicated for me than creating the app itself (I am a newbie dev starting with flutter).

I get an error when I try to launch my app that says the following: [!] Your project requires a newer version of the Kotlin Gradle plugin. Find the latest version on https://kotlinlang.org/docs/gradle.html#plugin-and-versions, then update C:\Users\User\Desktop\Dev\adtest\android\build.gradle: ext.kotlin_version = '' Exception: Gradle task assembleDebug failed with exit code 1

The problem seems simple, I have to update the field suggested by the console. My surprise is that the field ext.kotlin_version = " ", does not exist in my build.grade file on android/build.gradle. Neither does the buildscript { } apatagate exist that should contain it. I have android Studio installed, Flutter updated, I work with visual studio code, everything is apparently correct, except for this.

Thanks for your help.

答:
Add ext.kotlin_version and kotlin dependency in <app>/android/build.gradle file.

```<code>buildscript {
    ext.kotlin_version = '1.5.0' //use latest
    ...
}

dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    ...
}
</code>```

Body:
Add ext.kotlin_version and kotlin dependency in <app>/android/build.gradle file.

buildscript {
    ext.kotlin_version = '1.5.0' //use latest
    ...
}

dependencies {
    classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    ...
}


问:
How to fix this code? i tried WITH statement but it gave me an error
I tried to answer this question here in the code below, but it keeps giving me an error message!
I've tried to figure out how to

Provide the name of the sales_rep in each region with the largest amount of total_amt_usd sales?

and it gave me this Error :

aggregate function calls cannot be nested
ERD picture here

could you please help me with this?

```<code>WITH
    account_info AS (Select * from accounts),
    orders_info AS (select * from orders),
    region_info AS (select * from region),
    sales_reps_info AS (select * from sales_reps)

    SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders_info o
    JOIN account_info a
    ON o.account_id = a.id

    JOIN sales_reps_info s
    ON a.sales_rep_id = s.id

    JOIN region_info r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC
</code>```

答:
I'm not sure what you are attempting with with since you don't actually define a Common Table Expression.

That aside, your query is invalid, you cannot nest aggregate functions and you are already getting the max 100 by ordering and limiting rows, so I think you just want

```<code>SELECT s.name as rep_name, r.name as region_name, SUM (o.total_amt_usd) as Total
FROM orders_info o
JOIN account_info a ON o.account_id = a.id
JOIN sales_reps_info s ON a.sales_rep_id = s.id
JOIN region_info r ON r.id = s.region_id
GROUP BY REP_NAME, R.NAME
ORDER BY Total DESC
LIMIT 100;
</code>```

Body:
I tried to answer this question here in the code below, but it keeps giving me an error message!
I've tried to figure out how to

Provide the name of the sales_rep in each region with the largest amount of total_amt_usd sales?

and it gave me this Error :

aggregate function calls cannot be nested
ERD picture here

could you please help me with this?

WITH
    account_info AS (Select * from accounts),
    orders_info AS (select * from orders),
    region_info AS (select * from region),
    sales_reps_info AS (select * from sales_reps)

    SELECT s.name as rep_name, r.name as region_name, MAX (SUM (o.total_amt_usd)) as total
    FROM orders_info o
    JOIN account_info a
    ON o.account_id = a.id

    JOIN sales_reps_info s
    ON a.sales_rep_id = s.id

    JOIN region_info r
    ON r.id = s.region_id

    GROUP BY TOTAL, REP_NAME, R.NAME
    ORDER BY 3 DESC

Body:
I'm not sure what you are attempting with with since you don't actually define a Common Table Expression.

That aside, your query is invalid, you cannot nest aggregate functions and you are already getting the max 100 by ordering and limiting rows, so I think you just want

SELECT s.name as rep_name, r.name as region_name, SUM (o.total_amt_usd) as Total
FROM orders_info o
JOIN account_info a ON o.account_id = a.id
JOIN sales_reps_info s ON a.sales_rep_id = s.id
JOIN region_info r ON r.id = s.region_id
GROUP BY REP_NAME, R.NAME
ORDER BY Total DESC
LIMIT 100;


问:
Discord API - Get Discord role name from role ID
I'm using the Get Current User Guild Member method of Discord API.

I successfully get back information about user such as their role in a specific guild

```<code>roles: ['705175621399216228']
</code>```

How can I go from the role ID to the actual name of the role?

答:
https://discord.com/developers/docs/resources/guild#get-guild-roles
You can get all the role objects of the guild and filter the roles with the ID of the role you require.
You can use node-fetch, etc to get the roles with something like this

const fetch = require("node-fetch")
const data = await fetch("{base.url}/guilds/{guild.id}/roles")
const roleid = "xxxxxx"
const role = data.find(rl => rl.id === roleid)
```

Body:
I'm using the Get Current User Guild Member method of Discord API.

I successfully get back information about user such as their role in a specific guild

roles: ['705175621399216228']

How can I go from the role ID to the actual name of the role?


问:
How to rotate text manim
Is there anyway to rotate a

```<code>Text()
</code>```

in manim
I have tried using

```<code>Rotate(Text())
</code>```

it did not work .

答:
It is unclear whether or not you want to animate it; Rotate(some_text) is an animation and needs to be played.

In the community edition, you can run t.rotate(PI) to rotate without animation, and the Rotate animation from above like

```<code>def construct(self):
    t = Text("Hello World!")
    self.add(t)
    self.play(Rotate(t, angle=PI))
</code>```

to animate the rotation.

Title: How to rotate text manim

Body:
Is there anyway to rotate a

Text()

in manim
I have tried using

Rotate(Text())

it did not work .

Body:
It is unclear whether or not you want to animate it; Rotate(some_text) is an animation and needs to be played.

In the community edition, you can run t.rotate(PI) to rotate without animation, and the Rotate animation from above like

def construct(self):
    t = Text("Hello World!")
    self.add(t)
    self.play(Rotate(t, angle=PI))

to animate the rotation.


问:
Import functions from another directory
I am running a python script (app.py) where I have to use two functions from another script (src.py), located inside another directory. The structure is the following:

```<code>Dir:
   Dir_1:
        __init__.py
        src.py
   Dir_2:
        app.py
</code>```

I am using, in app.py, the following lines:

```<code>from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = PROJECT/'Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all
</code>```

to access to the functions odd_all, even_all declared inside src.py. However, I get the error: ModuleNotFoundError: No module named 'src'.

How could I solve this problem?

答:
I managed to solve the problem. The issue was that PROJECT is a Posixpath object, while SYS accepts only strings. Therefore, the solution was just to transform PROJECT to string:

```<code>from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = str(PROJECT)+'/Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all
</code>```

Now everything works perfectly.

Title: Import functions from another directory

Body:
I am running a python script (app.py) where I have to use two functions from another script (src.py), located inside another directory. The structure is the following:

Dir:
   Dir_1:
        __init__.py
        src.py
   Dir_2:
        app.py

I am using, in app.py, the following lines:

from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = PROJECT/'Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all

to access to the functions odd_all, even_all declared inside src.py. However, I get the error: ModuleNotFoundError: No module named 'src'.

How could I solve this problem?

Body:
I managed to solve the problem. The issue was that PROJECT is a Posixpath object, while SYS accepts only strings. Therefore, the solution was just to transform PROJECT to string:

from pathlib import Path
PROJECT = Path(__file__).resolve().parent.parent
PROJECT = str(PROJECT)+'/Dir_1'

import sys
sys.path.insert(1, PROJECT)
from src import odd_all, even_all

Now everything works perfectly.


问:
Showing particular row data as column
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

```<code>        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE
</code>```

Your help will be very appreciated.

答:
Im sure theres a more efficient way of doing this, but heres a way to solve your issue using 2 subqueries:

```<code>SELECT t1.*, (SELECT t2.MA5
              FROM tableA t2
              WHERE t1.date = t2.date
              AND code = 'NASDAQ') as NASDAQ_MA5,
              (SELECT t2.MA20
              FROM tableA t2
              WHERE t1.date = t2.date
              AND code = 'NASDAQ') as NASDAQ_MA20
FROM tableA t1
WHERE code != 'NASDAQ'
</code>```

Try it out here.

Title: Showing particular row data as column

Body:
My table is as follows:

Date
Code
Price
MA5
MA20

2022-01-01
APPLE
1000
1080
1090

2022-01-02
APPLE
1100
1084
1100

2022-01-03
APPLE
1200
1090
1100

2022-01-01
MICROSOFT
7
9
10

2022-01-02
MICROSOFT
7.5
8
9.5

2022-01-03
MICROSOFT
8
8.5
9

...
...
...
...
...

2022-01-01
NASDAQ
14400
15600
16700

2022-01-02
NASDAQ
14500
15200
16100

2022-01-03
NASDAQ
14600
15000
16000

I'm currently saving NASDAQ values and stock data on the same table using MariaDB.

However, I want to show NASDAQ's MA values as new column fields into rest of the field, as NASDAQ_MA5, NASDAQ_MA20.

My question is, how do I select nasdaq's MA5 and MA20 values and put it as the values according to the matching dates? My desired output is as follows:

Date
Code
Price
MA5
MA20
NASDAQ_MA5
NASDAQ_MA20

2022-01-01
APPLE
1000
1080
1090
15600
16700

2022-01-02
APPLE
1100
1084
1100
15200
16100

2022-01-03
APPLE
1200
1090
1100
15000
16000

2022-01-01
MICROSOFT
7
9
10
15600
16700

2022-01-02
MICROSOFT
7.5
8
9.5
15200
16100

2022-01-03
MICROSOFT
8
8.5
9
15000
16000

I've been trying the following:

        SELECT *,
        (PARTITION BY DATE, case when (code='NASDAQ') then MA5 else NULL end) as 'NASDAQ_MA5',
        (PARTITION BY DATE, case when (code='NASDAQ') then MA20 else NULL end) as 'NASDAQ_MA20'
        FROM TABLE

Your help will be very appreciated.

Body:
Im sure theres a more efficient way of doing this, but heres a way to solve your issue using 2 subqueries:

SELECT t1.*, (SELECT t2.MA5
              FROM tableA t2
              WHERE t1.date = t2.date
              AND code = 'NASDAQ') as NASDAQ_MA5,
              (SELECT t2.MA20
              FROM tableA t2
              WHERE t1.date = t2.date
              AND code = 'NASDAQ') as NASDAQ_MA20
FROM tableA t1
WHERE code != 'NASDAQ'

Try it out here.


问:
How to fill polygons with colors based on a variable in Matplotlib?
I've been working with a shapefile that has the x and y coordinates of the vertices of several buildings, and I am using Matplotlib to plot them as polygons. However, I would like to fill these polygons with shades of red/grey/or any other color based on the number of floors each building has. For example, the minimum number of floors is zero, so all buildings with zero floors would be of very light color. On the other hand, the maximum number of floors is 100, so all buildings with a hundred floors would plot very dark, and between 0 and 100 the polygons would plot darker and darker as the number of floors increased.

I found a few things online but nothing that tackles this specifically. I am new at Python so maybe I am just not aware of the right library that can do what I need.

My code for now is this: (It plots the polygons only, no fill)

```<code>import shapefile
import matplotlib.pyplot as plt
import numpy as np

i = 0
sf = shapefile.Reader('shapefile')
sr = sf.shapeRecords()
max = 10

while i < max:
    sr_obj = sr[i]
    sr_points = np.array(sr_obj.shape.points)
    records = sf.record(i)
    numfloors = records[42]
    x = sr_points[:,0]
    y = sr_points[:,1]
    sr_plot = zip(*sr_points)
    plt.plot(*sr_plot)
    i = i + 1

plt.show()
</code>```

Thank you!

答:
Just to add to @Marjin van Cliet's answer, you could use a dictionary to map a vector of floor numbers to colors, obviously you would need to also set the polygon corners from the dataset too in the loop.</p>
```<code>from matplotlib.patches import Polygon
import matplotlib.pyplot as plt

nfs=[2,3,1,2,3] # number of floors
cols={"1":"red","2":"blue","3":"orange"}

plt.figure()
axes = plt.gca()
for nf in nfs:
    axes.add_patch(Polygon([(0, 0), (1, 0.2), (0.3, 0.4), (0.2, 1)],
                       closed=True, facecolor=cols[str(nf)]))
</code>```

Body:
I've been working with a shapefile that has the x and y coordinates of the vertices of several buildings, and I am using Matplotlib to plot them as polygons. However, I would like to fill these polygons with shades of red/grey/or any other color based on the number of floors each building has. For example, the minimum number of floors is zero, so all buildings with zero floors would be of very light color. On the other hand, the maximum number of floors is 100, so all buildings with a hundred floors would plot very dark, and between 0 and 100 the polygons would plot darker and darker as the number of floors increased.

I found a few things online but nothing that tackles this specifically. I am new at Python so maybe I am just not aware of the right library that can do what I need.

My code for now is this: (It plots the polygons only, no fill)

import shapefile
import matplotlib.pyplot as plt
import numpy as np

i = 0
sf = shapefile.Reader('shapefile')
sr = sf.shapeRecords()
max = 10

while i < max:
    sr_obj = sr[i]
    sr_points = np.array(sr_obj.shape.points)
    records = sf.record(i)
    numfloors = records[42]
    x = sr_points[:,0]
    y = sr_points[:,1]
    sr_plot = zip(*sr_points)
    plt.plot(*sr_plot)
    i = i + 1

plt.show()

Thank you!

Body:
Just to add to @Marjin van Cliet's answer, you could use a dictionary to map a vector of floor numbers to colors, obviously you would need to also set the polygon corners from the dataset too in the loop.

from matplotlib.patches import Polygon
import matplotlib.pyplot as plt

nfs=[2,3,1,2,3] # number of floors
cols={"1":"red","2":"blue","3":"orange"}

plt.figure()
axes = plt.gca()
for nf in nfs:
    axes.add_patch(Polygon([(0, 0), (1, 0.2), (0.3, 0.4), (0.2, 1)],
                       closed=True, facecolor=cols[str(nf)]))


问:
Getting permission denied even as root inside the docker container
Connecting to running docker container as a root still gets Operation not permitted error when trying to apt-get update, yet I can still see sensitive file like /etc/passwd. Below are my configurations and also the error message from apt-get update. My host operating system is Ubuntu 18.04.3. My docker version is Docker version 19.03.5, build 633a0ea838

I create a container with the following Dockerfile

```<code>FROM python:3.8-slim-buster
RUN useradd -ms /bin/bash andrej
WORKDIR /home/andrej
COPY . /home/andrej/

RUN apt-get update && \
    apt-get install -y gcc && \
    pip install -r requirements.txt && \
    apt-get remove -y gcc && apt-get -y autoremove

RUN chown andrej:andrej pycurl && \
    chmod 0744 pycurl

USER andrej
ENTRYPOINT ["uwsgi"]
CMD ["--ini", "uwsgi.ini"]

</code>```

starting it with docker compose looking like this:

```<code>version: "3.3"

services:

  andrej-cv:
    build: ./andrej_cv
    container_name: andrej-cv
    restart: always
    security_opt:
      - no-new-privileges
    expose:
      - 5000
    healthcheck:
      test: ./pycurl --host=127.0.0.1 --port=5050 --uri=/health_check
      interval: 1m30s
      timeout: 10s
      retries: 3
</code>```

My docker daemon config:

```<code>{
    "icc": false,
    "userns-remap": "default",
    "log-driver": "syslog",
    "live-restore": true,
    "userland-proxy": false,
    "no-new-privileges": true
}

</code>```

I connect to the container with following command (as root):
docker exec -it -u root <container_hash> /bin/bash but when I try to update I got the following:

```<code>root@ed984abff684:/home/andrej# apt-get update
E: setgroups 65534 failed - setgroups (1: Operation not permitted)
E: setegid 65534 failed - setegid (1: Operation not permitted)
E: seteuid 100 failed - seteuid (1: Operation not permitted)
E: setgroups 0 failed - setgroups (1: Operation not permitted)
Hit:1 http://deb.debian.org/debian buster InRelease
Ign:2 http://deb.debian.org/debian buster-updates InRelease
Err:4 http://deb.debian.org/debian buster-updates Release
  Could not open file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_Release - open (13: Permission denied) [IP: 151.101.36.204 80]
Hit:3 http://security-cdn.debian.org/debian-security buster/updates InRelease
rm: cannot remove '/var/cache/apt/archives/partial/*.deb': Permission denied
Reading package lists... Done
W: chown to _apt:root of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chown to _apt:root of directory /var/lib/apt/lists/auxfiles failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chmod 0700 of directory /var/lib/apt/lists/auxfiles failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: setgroups 65534 failed - setgroups (1: Operation not permitted)
E: setegid 65534 failed - setegid (1: Operation not permitted)
E: seteuid 100 failed - seteuid (1: Operation not permitted)
W: Download is performed unsandboxed as root as file '/var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster_InRelease' couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
E: setgroups 0 failed - setgroups (1: Operation not permitted)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster_InRelease - PrepareFiles (13: Permission denied)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_InRelease - PrepareFiles (13: Permission denied)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_Release - PrepareFiles (13: Permission denied)
E: The repository 'http://deb.debian.org/debian buster-updates Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: Problem unlinking the file /var/lib/apt/lists/partial/security.debian.org_debian-security_dists_buster_updates_InRelease - PrepareFiles (13: Permission denied)
</code>```

In the container /etc/subuid and /etc/subgid look like this (both):

```<code>andrej:100000:65536
</code>```

On the host /etc/subuid and /etc/subgid look like this (both):

```<code>andrej:100000:65536
dockremap:165536:65536
</code>```

Apparmor is running on Ubuntu host with following status (only docker-default profile):

```<code>andrej@machine:/etc/apparmor.d$ sudo aa-status
apparmor module is loaded.
38 profiles are loaded.
36 profiles are in enforce mode.
   /sbin/dhclient
   /snap/core/8268/usr/lib/snapd/snap-confine
   /snap/core/8268/usr/lib/snapd/snap-confine//mount-namespace-capture-helper
   /usr/bin/evince
   /usr/bin/evince-previewer
   /usr/bin/evince-previewer//sanitized_helper
   /usr/bin/evince-thumbnailer
   /usr/bin/evince//sanitized_helper
   /usr/bin/man
   /usr/lib/NetworkManager/nm-dhcp-client.action
   /usr/lib/NetworkManager/nm-dhcp-helper
   /usr/lib/connman/scripts/dhclient-script
   /usr/lib/cups/backend/cups-pdf
   /usr/lib/snapd/snap-confine
   /usr/lib/snapd/snap-confine//mount-namespace-capture-helper
   /usr/sbin/cups-browsed
   /usr/sbin/cupsd
   /usr/sbin/cupsd//third_party
   /usr/sbin/ippusbxd
   /usr/sbin/tcpdump
   docker-default
   libreoffice-senddoc
   libreoffice-soffice//gpg
   libreoffice-xpdfimport
   man_filter
   man_groff
   snap-update-ns.core
   snap-update-ns.gnome-calculator
   snap-update-ns.gnome-characters
   snap-update-ns.gnome-logs
   snap-update-ns.gnome-system-monitor
   snap.core.hook.configure
   snap.gnome-calculator.gnome-calculator
   snap.gnome-characters.gnome-characters
   snap.gnome-logs.gnome-logs
   snap.gnome-system-monitor.gnome-system-monitor
2 profiles are in complain mode.
   libreoffice-oopslash
   libreoffice-soffice
17 processes have profiles defined.
14 processes are in enforce mode.
   docker-default (1101)
   docker-default (1102)
   docker-default (1111)
   docker-default (1600)
   docker-default (1728)
   docker-default (1729)
   docker-default (1730)
   docker-default (1731)
   docker-default (1732)
   docker-default (1798)
   docker-default (1799)
   docker-default (1800)
   docker-default (1801)
   docker-default (1802)
0 processes are in complain mode.
3 processes are unconfined but have a profile defined.
   /sbin/dhclient (491)
   /usr/sbin/cups-browsed (431)
   /usr/sbin/cupsd (402)
</code>```

Selinux seems to be disabled as there is not /etc/selinux/config file and getenfoce and sestatus command are not available.

Also su andrej command run as root (where andrej is unprivileged user in the container) errors out with su: cannot set groups: Operation not permitted

答:
The docker container you describe is working as designed. With the default capabilities.

Fast test if you have a missing capability.

Run your container with Full/All container capabilities (--privileged)

More explanations about capabilities from Docker documentation

The Linux kernel is able to break down the privileges of the root user
into distinct units referred to as capabilities. For example, the
CAP_CHOWN capability is what allows the root user to make arbitrary
changes to file UIDs and GIDs. The CAP_DAC_OVERRIDE capability allows
the root user to bypass kernel permission checks on file read, write
and execute operations. Almost all of the special powers associated
with the Linux root user are broken down into individual capabilities.

This breaking down of root privileges into granular capabilities
allows you to:

```<code>Remove individual capabilities from the root user account, making it less powerful/dangerous.
Add privileges to non-root users at a very granular level.
</code>```

Capabilities apply to both files and threads. File capabilities allow
users to execute programs with higher privileges. This is similar to
the way the setuid bit works. Thread capabilities keep track of the
current state of capabilities in running programs.

The Linux kernel lets you set capability bounding sets that impose
limits on the capabilities that a file/thread can gain.

Docker imposes certain limitations that make working with capabilities
much simpler. For example, file capabilities are stored within a
file’s extended attributes, and extended attributes are stripped out
when Docker images are built. This means you will not normally have to
concern yourself too much with file capabilities in containers.

```<code>It is of course possible to get file capabilities into containers at runtime, however this is not recommended.
</code>```

In an environment without file based capabilities, it’s not possible
for applications to escalate their privileges beyond the bounding set
(a set beyond which capabilities cannot grow). Docker sets the
bounding set before starting a container. You can use Docker commands
to add or remove capabilities to or from the bounding set.

By default, Docker drops all capabilities except those needed, using a
whitelist approach.

Body:
Connecting to running docker container as a root still gets Operation not permitted error when trying to apt-get update, yet I can still see sensitive file like /etc/passwd. Below are my configurations and also the error message from apt-get update. My host operating system is Ubuntu 18.04.3. My docker version is Docker version 19.03.5, build 633a0ea838

I create a container with the following Dockerfile

FROM python:3.8-slim-buster
RUN useradd -ms /bin/bash andrej
WORKDIR /home/andrej
COPY . /home/andrej/

RUN apt-get update && \
    apt-get install -y gcc && \
    pip install -r requirements.txt && \
    apt-get remove -y gcc && apt-get -y autoremove

RUN chown andrej:andrej pycurl && \
    chmod 0744 pycurl

USER andrej
ENTRYPOINT ["uwsgi"]
CMD ["--ini", "uwsgi.ini"]

starting it with docker compose looking like this:

version: "3.3"

services:

  andrej-cv:
    build: ./andrej_cv
    container_name: andrej-cv
    restart: always
    security_opt:
      - no-new-privileges
    expose:
      - 5000
    healthcheck:
      test: ./pycurl --host=127.0.0.1 --port=5050 --uri=/health_check
      interval: 1m30s
      timeout: 10s
      retries: 3

My docker daemon config:

{
    "icc": false,
    "userns-remap": "default",
    "log-driver": "syslog",
    "live-restore": true,
    "userland-proxy": false,
    "no-new-privileges": true
}

I connect to the container with following command (as root):
docker exec -it -u root <container_hash> /bin/bash but when I try to update I got the following:

root@ed984abff684:/home/andrej# apt-get update
E: setgroups 65534 failed - setgroups (1: Operation not permitted)
E: setegid 65534 failed - setegid (1: Operation not permitted)
E: seteuid 100 failed - seteuid (1: Operation not permitted)
E: setgroups 0 failed - setgroups (1: Operation not permitted)
Hit:1 http://deb.debian.org/debian buster InRelease
Ign:2 http://deb.debian.org/debian buster-updates InRelease
Err:4 http://deb.debian.org/debian buster-updates Release
  Could not open file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_Release - open (13: Permission denied) [IP: 151.101.36.204 80]
Hit:3 http://security-cdn.debian.org/debian-security buster/updates InRelease
rm: cannot remove '/var/cache/apt/archives/partial/*.deb': Permission denied
Reading package lists... Done
W: chown to _apt:root of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chmod 0700 of directory /var/lib/apt/lists/partial failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chown to _apt:root of directory /var/lib/apt/lists/auxfiles failed - SetupAPTPartialDirectory (1: Operation not permitted)
W: chmod 0700 of directory /var/lib/apt/lists/auxfiles failed - SetupAPTPartialDirectory (1: Operation not permitted)
E: setgroups 65534 failed - setgroups (1: Operation not permitted)
E: setegid 65534 failed - setegid (1: Operation not permitted)
E: seteuid 100 failed - seteuid (1: Operation not permitted)
W: Download is performed unsandboxed as root as file '/var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster_InRelease' couldn't be accessed by user '_apt'. - pkgAcquire::Run (13: Permission denied)
E: setgroups 0 failed - setgroups (1: Operation not permitted)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster_InRelease - PrepareFiles (13: Permission denied)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_InRelease - PrepareFiles (13: Permission denied)
W: Problem unlinking the file /var/lib/apt/lists/partial/deb.debian.org_debian_dists_buster-updates_Release - PrepareFiles (13: Permission denied)
E: The repository 'http://deb.debian.org/debian buster-updates Release' no longer has a Release file.
N: Updating from such a repository can't be done securely, and is therefore disabled by default.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: Problem unlinking the file /var/lib/apt/lists/partial/security.debian.org_debian-security_dists_buster_updates_InRelease - PrepareFiles (13: Permission denied)

In the container /etc/subuid and /etc/subgid look like this (both):

andrej:100000:65536

On the host /etc/subuid and /etc/subgid look like this (both):

andrej:100000:65536
dockremap:165536:65536

Apparmor is running on Ubuntu host with following status (only docker-default profile):

andrej@machine:/etc/apparmor.d$ sudo aa-status
apparmor module is loaded.
38 profiles are loaded.
36 profiles are in enforce mode.
   /sbin/dhclient
   /snap/core/8268/usr/lib/snapd/snap-confine
   /snap/core/8268/usr/lib/snapd/snap-confine//mount-namespace-capture-helper
   /usr/bin/evince
   /usr/bin/evince-previewer
   /usr/bin/evince-previewer//sanitized_helper
   /usr/bin/evince-thumbnailer
   /usr/bin/evince//sanitized_helper
   /usr/bin/man
   /usr/lib/NetworkManager/nm-dhcp-client.action
   /usr/lib/NetworkManager/nm-dhcp-helper
   /usr/lib/connman/scripts/dhclient-script
   /usr/lib/cups/backend/cups-pdf
   /usr/lib/snapd/snap-confine
   /usr/lib/snapd/snap-confine//mount-namespace-capture-helper
   /usr/sbin/cups-browsed
   /usr/sbin/cupsd
   /usr/sbin/cupsd//third_party
   /usr/sbin/ippusbxd
   /usr/sbin/tcpdump
   docker-default
   libreoffice-senddoc
   libreoffice-soffice//gpg
   libreoffice-xpdfimport
   man_filter
   man_groff
   snap-update-ns.core
   snap-update-ns.gnome-calculator
   snap-update-ns.gnome-characters
   snap-update-ns.gnome-logs
   snap-update-ns.gnome-system-monitor
   snap.core.hook.configure
   snap.gnome-calculator.gnome-calculator
   snap.gnome-characters.gnome-characters
   snap.gnome-logs.gnome-logs
   snap.gnome-system-monitor.gnome-system-monitor
2 profiles are in complain mode.
   libreoffice-oopslash
   libreoffice-soffice
17 processes have profiles defined.
14 processes are in enforce mode.
   docker-default (1101)
   docker-default (1102)
   docker-default (1111)
   docker-default (1600)
   docker-default (1728)
   docker-default (1729)
   docker-default (1730)
   docker-default (1731)
   docker-default (1732)
   docker-default (1798)
   docker-default (1799)
   docker-default (1800)
   docker-default (1801)
   docker-default (1802)
0 processes are in complain mode.
3 processes are unconfined but have a profile defined.
   /sbin/dhclient (491)
   /usr/sbin/cups-browsed (431)
   /usr/sbin/cupsd (402)

Selinux seems to be disabled as there is not /etc/selinux/config file and getenfoce and sestatus command are not available.

Also su andrej command run as root (where andrej is unprivileged user in the container) errors out with su: cannot set groups: Operation not permitted

Body:
The docker container you describe is working as designed. With the default capabilities.

Fast test if you have a missing capability.

Run your container with Full/All container capabilities (--privileged)

More explanations about capabilities from Docker documentation

The Linux kernel is able to break down the privileges of the root user
into distinct units referred to as capabilities. For example, the
CAP_CHOWN capability is what allows the root user to make arbitrary
changes to file UIDs and GIDs. The CAP_DAC_OVERRIDE capability allows
the root user to bypass kernel permission checks on file read, write
and execute operations. Almost all of the special powers associated
with the Linux root user are broken down into individual capabilities.

This breaking down of root privileges into granular capabilities
allows you to:

Remove individual capabilities from the root user account, making it less powerful/dangerous.
Add privileges to non-root users at a very granular level.

Capabilities apply to both files and threads. File capabilities allow
users to execute programs with higher privileges. This is similar to
the way the setuid bit works. Thread capabilities keep track of the
current state of capabilities in running programs.

The Linux kernel lets you set capability bounding sets that impose
limits on the capabilities that a file/thread can gain.

Docker imposes certain limitations that make working with capabilities
much simpler. For example, file capabilities are stored within a
file’s extended attributes, and extended attributes are stripped out
when Docker images are built. This means you will not normally have to
concern yourself too much with file capabilities in containers.

It is of course possible to get file capabilities into containers at runtime, however this is not recommended.

In an environment without file based capabilities, it’s not possible
for applications to escalate their privileges beyond the bounding set
(a set beyond which capabilities cannot grow). Docker sets the
bounding set before starting a container. You can use Docker commands
to add or remove capabilities to or from the bounding set.

By default, Docker drops all capabilities except those needed, using a
whitelist approach.


问:
Create dictionary of context words without stopwords
I am trying to create a dictionary of words in a text and their context. The context should be the list of words that occur within a 5 word window (two words on either side) of the term's position in the string. Effectively, I want to ignore the stopwords in my output vectors.

My code is below. I can get the stopwords out of my dictionary's keys but not the values.

```<code>words = ["This", "is", "an", "example", "sentence" ]
stopwords = ["it", "the", "was", "of"]
context_size = 2

stripes = {word:words[max(i - context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1)) if word.lower() not in stopwords}
print(stripes)
</code>```

the output is:

```<code>{'example': ['is', 'an', 'example', 'sentence'], 'sentence': ['an', 'example', 'sentence']}
</code>```

答:
```<code>words = ["This", "is", "a", "longer", "example", "sentence"]
stopwords = set(["it", "the", "was", "of", "is", "a"])
context_size = 2

stripes = []
for index, word in enumerate(words):
    if word.lower() in stopwords:
        continue
    i = max(index - context_size, 0)
    j = min(index + context_size, len(words) - 1) + 1
    context = words[i:index] + words[index + 1:j]
    stripes.append((word, context))

print(stripes)
</code>```

I would recommend to use a tuple list so in case a word occurs more than once in words the dict does not just contain the last one which overwrites previous ones. I would also put stopwords in a set, especially if its a larger list like NLTKs stopwords since that speeds up things.

I also excluded the word itself from the context but depending on how you want to use it you might want to include it.

This results in:

```<code>[('This', ['is', 'a']), ('longer', ['is', 'a', 'example', 'sentence']), ('example', ['a', 'longer', 'sentence']), ('sentence', ['longer', 'example'])]
</code>```

Body:
I am trying to create a dictionary of words in a text and their context. The context should be the list of words that occur within a 5 word window (two words on either side) of the term's position in the string. Effectively, I want to ignore the stopwords in my output vectors.

My code is below. I can get the stopwords out of my dictionary's keys but not the values.

words = ["This", "is", "an", "example", "sentence" ]
stopwords = ["it", "the", "was", "of"]
context_size = 2

stripes = {word:words[max(i - context_size,0):j] for word,i,j in zip(words,count(0),count(context_size+1)) if word.lower() not in stopwords}
print(stripes)

the output is:

{'example': ['is', 'an', 'example', 'sentence'], 'sentence': ['an', 'example', 'sentence']}

Body:
words = ["This", "is", "a", "longer", "example", "sentence"]
stopwords = set(["it", "the", "was", "of", "is", "a"])
context_size = 2

stripes = []
for index, word in enumerate(words):
    if word.lower() in stopwords:
        continue
    i = max(index - context_size, 0)
    j = min(index + context_size, len(words) - 1) + 1
    context = words[i:index] + words[index + 1:j]
    stripes.append((word, context))

print(stripes)

I would recommend to use a tuple list so in case a word occurs more than once in words the dict does not just contain the last one which overwrites previous ones. I would also put stopwords in a set, especially if its a larger list like NLTKs stopwords since that speeds up things.

I also excluded the word itself from the context but depending on how you want to use it you might want to include it.

This results in:

[('This', ['is', 'a']), ('longer', ['is', 'a', 'example', 'sentence']), ('example', ['a', 'longer', 'sentence']), ('sentence', ['longer', 'example'])]