问:
Overlay Text on a Centered Image Which Is Smaller Than Its Containing Element
I have the following case:

Image which its width is less than the page width.

Image needs to be centered within its parent div (Which is wider).

Overlay text should be displayed on the image on one of its corners.

Image can not be stretched. Image will appear in its native size.

The image size can not be set in CSS as this template will be used for many images in different size.

So the code I came up with is given in https://jsfiddle.net/RoyiA/gdezys7j Or (Must be viewed in Full Screen so the image will be centered):

@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}

.image-container {
   position: relative;
   font-family: Arial;
}

.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}

.image-text-block {
   position: absolute;
display: block;
   top: 100px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding-left: 10px;
   padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-container">
 <img class="image-center" src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
   <div class="image-text-block">
     <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
     <p>Image: Jane by Mireille Lannoo</p>
   </div>
</div></code>```

The problem I'm having is that the text div is relative to the position of its parent div while the image is centered. How can address that?

答:
I would suggest wrapping the image-container block inside another div which purpose is to center it. That way the image-container block has the width of the image and your absolute positioning of the caption box should work as intended.

.image-container {
  position: relative;
  font-family: Arial;
}

.image-center {
  display: flex;
  justify-content: center;
}

.image-center img {
  display: block;
}

.image-text-block {
  position: absolute;
  display: block;
  top: 10px;
  left: 10px;
  background-color: rgba(100, 100, 100, .5);
  color: white;
  padding-left: 10px;
  padding-right: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-center">
  <div class="image-container">
    <img src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
    <div class="image-text-block">
      <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
      <p>Image: Jane by Mireille Lannoo</p>
    </div>
  </div>
</div></code>```

Body:
I have the following case:

Image which its width is less than the page width.

Image needs to be centered within its parent div (Which is wider).

Overlay text should be displayed on the image on one of its corners.

Image can not be stretched. Image will appear in its native size.

The image size can not be set in CSS as this template will be used for many images in different size.

So the code I came up with is given in https://jsfiddle.net/RoyiA/gdezys7j Or (Must be viewed in Full Screen so the image will be centered):

@font-face {font-family: "MammaGamma";
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot");
src: url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.eot?#iefix") format("embedded-opentype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff2") format("woff2"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.woff") format("woff"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.ttf") format("truetype"),
url("//db.onlinewebfonts.com/t/1d8209e6e1d626b5657d1a5b99ea9572.svg#MammaGamma") format("svg");
}

.image-container {
   position: relative;
   font-family: Arial;
}

.image-center{
position: relative;
display: block;
margin-left: auto;
margin-right: auto;
}

.image-text-block {
   position: absolute;
display: block;
   top: 100px;
   left: 10px;
   background-color: rgba(100, 100, 100, 0.5);
   color: white;
   padding-left: 10px;
   padding-right: 10px;
}

Image Text Blocks

How to place text blocks over an image:

Created with Photoshop

Image: Jane by Mireille Lannoo

The problem I'm having is that the text div is relative to the position of its parent div while the image is centered. How can address that?

Body:
I would suggest wrapping the image-container block inside another div which purpose is to center it. That way the image-container block has the width of the image and your absolute positioning of the caption box should work as intended.

.image-container {
  position: relative;
  font-family: Arial;
}

.image-center {
  display: flex;
  justify-content: center;
}

.image-center img {
  display: block;
}

.image-text-block {
  position: absolute;
  display: block;
  top: 10px;
  left: 10px;
  background-color: rgba(100, 100, 100, .5);
  color: white;
  padding-left: 10px;
  padding-right: 10px;
}

<h2>Image Text Blocks</h2>
<p>How to place text blocks over an image:</p>

<div class="image-center">
  <div class="image-container">
    <img src="https://i.imgur.com/0s8kLb7.png" alt="Nature">
    <div class="image-text-block">
      <h3>Created with <span style="font-family:MammaGamma; color:rgb(239, 74, 74)">Photoshop</span></h3>
      <p>Image: <a href="https://www.flickr.com/photos/151740882@N05/47029584231">Jane</a> by Mireille Lannoo</p>
    </div>
  </div>
</div>


来源: stackexchange

问:
Dynamic value in multiple React Native Modal
I have 6 dropdowns in a vehicle compare screen. Dropdowns are created with React Modal. All the data in the dropdowns are dynamic.

When the page is loaded data to be shown in the first two modals, car brands, are fetched and they are shown in modals are dropdown.

When a car brand is selected another api call is made to get the models available in that brand. This data is populated on the second dropdown.

Since there is two dropdowns for selecting model for two different brands, when one brand is selected both the model dropdowns get updated.

How can I change my code such that i can make this work and make it scalable in future if i have to add more number of cars fo comparing?

Compare.js

```<code>import React, { Component } from 'react'
import {
    View,
    StyleSheet,
    ScrollView,
    SafeAreaView,
    ActivityIndicator,
} from 'react-native';

import PickerModal from '../components/PickerModal';
import * as Api from "../api/app";

export default class CompareVehicles extends Component {
    constructor (props) {
        super(props);
        this.state = {
            isLoading: true,
            vehicleCompany: [],
            vehicleModel: [],
            vehicleSubModel: [],
        };
    }

    componentDidMount() {
        this.setState({
            isLoading: true,
        });
        this.getVehicleBrand();
    }

    getVehicleBrand = () => {
        Api.getVehicleBrands()
            .then((responseJson) => {
                console.log(responseJson);
                if (responseJson.success === true){
                    this.setState({
                        isLoading: false,
                        vehicleCompany : responseJson.data
                    });
                }  else {
                    alert("Error Loading Content")
                }
            });
    };

    submitBrand = async (data) => {
        Api.getVehicleModel(data)
            .then((responseJson) => {
                console.log(responseJson);
                if (responseJson.success === true){
                    this.setState({
                        vehicleModel: responseJson.data
                    });
                }  else {
                    alert("Error Adding Content")
                }
            });
    };

    submitModel = (data) => {
        console.log(data)
    };

    submitVariant = (data) => {
        console.log(data)
    };

    _renderPickerModal = (index) => {
        if (this.state.vehicleSubModel.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                    <PickerModal onSubmit={this.submitModel} type={'light-dropdown'} data={this.state.vehicleModel}/>
                    <PickerModal onSubmit={this.submitVariant} type={'light-dropdown'} data={this.state.vehicleSubModel}/>
                </View>
            )
        } else if(this.state.vehicleModel.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                    <PickerModal onSubmit={this.submitModel} type={'light-dropdown'} data={this.state.vehicleModel}/>
                </View>
            )
        } else if (this.state.vehicleCompany.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                </View>
            )
        }
    };

    render() {
        if(this.state.isLoading) {
            return (
                <SafeAreaView style={[styles.safeArea, styles.alignJustifyCenter]}>
                    <ActivityIndicator/>
                </SafeAreaView>
            );
        } else {
            return (
                <SafeAreaView style={styles.safeArea}>
                    <ScrollView
                        style={styles.scrollView}
                        scrollEventThrottle={200}
                        directionalLockEnabled={true}>
                        <View style={{flexDirection: 'row'}}>
                            <View style={{flex: 1}}>
                                {this._renderPickerModal}
                            </View>
                            <View style={{flex: 1}}>
                                {this._renderPickerModal}
                            </View>
                        </View>
                    </ScrollView>
                </SafeAreaView>
            );
        }
    }
}

const styles = StyleSheet.create({
    safeArea: {
        flex: 1,
        backgroundColor: '#ffffff',
    },
    alignJustifyCenter: {
        alignItems: 'center',
        justifyContent: 'center'
    },
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
        paddingVertical: 15,
        paddingHorizontal: 20
    }
});
</code>```

PickerModal.js

```<code>import React, {Component} from 'react';
import { StyleSheet, Text, View, Modal, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback } from 'react-native';
import PropTypes from 'prop-types';
import Ionicons from 'react-native-vector-icons/Ionicons';

export default class PickerModal extends Component {
    static propTypes = {
        type: PropTypes.string.isRequired,
        data: PropTypes.array.isRequired,
        onSubmit: PropTypes.func.isRequired,
        index: PropTypes.number
    };

    constructor(props) {
        super(props);

        this.state = {
            pickerTitle: this.props.data[0].name,
            pickerValue: this.props.data[0].id,
            pickerDisplayed: false,
            index: this.props.index
        }
    }

    componentDidMount = () => {
        console.log(this.props)
    };

    submit = () => {
        const { pickerValue } = this.state;
        const { index } = this.state;
        if (pickerValue) {
            this.props.onSubmit(pickerValue, index);
        }
    };

    setPickerValue(content, index) {
        this.setState({
            pickerTitle: content.name,
            pickerValue: content.id,
            index: index
        }, () => this.submit());

        this.togglePicker();
    }

    togglePicker() {
        this.setState({
            pickerDisplayed: !this.state.pickerDisplayed
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight
                    style={{width: '90%'}}
                    onPress={() => this.togglePicker()}
                    underlayColor='transparent'>
                    <View style={[styles.dropdown, this.props.type == 'dark-dropdown' ? styles.darkDropdown : styles.lightDropdown]}>
                        <Text style={[this.props.type == 'dark-dropdown' ? styles.darkDropdown : {}, {flex: 1}]}>{this.state.pickerTitle}</Text>
                        <Ionicons name={'md-arrow-dropdown'} size={25} style={[this.props.type == 'dark-dropdown' ? styles.colorWhite : {}, {marginLeft: 5, marginTop: 5}]}/>
                    </View>
                </TouchableHighlight>
                <Modal visible={this.state.pickerDisplayed} animationType={"fade"} transparent={true}>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{flex:1, justifyContent:'center', alignItems:'center', backgroundColor: 'rgba(0, 0, 0, 0.3)'}}
                        onPressOut={() => {this.togglePicker()}}>
                        <TouchableWithoutFeedback>
                            <View style={{padding: 20,
                                backgroundColor: '#ffffff',
                                bottom: 0,
                                left: 0,
                                right: 0,
                                alignItems: 'center',
                                position: 'absolute', width: '100%' }}>
                                { this.props.data.map((value, index) => {
                                    return <TouchableHighlight key={index} onPress={() => this.setPickerValue(value, this.props.index)} style={{ paddingTop: 4, paddingBottom: 4 }}>
                                        <Text style={{fontSize: 15}}>{ value.name }</Text>
                                    </TouchableHighlight>
                                })}

                                <TouchableHighlight onPress={() => this.togglePicker()} style={{ paddingTop: 50, paddingBottom: 20 }}>
                                    <Text style={{color: '#999', fontSize: 20}}>Cancel</Text>
                                </TouchableHighlight>
                            </View>
                        </TouchableWithoutFeedback>
                    </TouchableOpacity>
                </Modal>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    colorWhite: {
        color: '#fff'
    },
    darkDropdown: {
        backgroundColor: '#000',
        borderRadius: 8,
        color: '#fff'
    },
    lightDropdown: {
        borderBottomWidth: 0.3,
        borderBottomColor: '#000'
    },
    dropdown: {
        flexDirection: 'row',
        paddingHorizontal: 5,
        paddingVertical: 0,
        alignItems: 'center',
        justifyContent: 'center',
    }
});
</code>```

答:
I believe what you are doing is close enough. I'd create an intermediate ContainerComponent that should receive the brand and be completely isolated from the amount of cars that need to compare.

You just do something like:

```<code>render(){
     this.state.brandsToCompare.map(brand => <PickerModalContainer brand={brand}/>)
}
</code>```

So the main Component will only be responsible for managing if the user picks 1, 2, or any amount of brands or cars they want to compare. The PickerModalContainer will have the logic for the fetching and depending on what the user selects, you just fetch and update the other PickerModals. This way you really don't care about the other Pickers, since they don't "know" each other.

If, at the end you need to get some information to compare, you can expose functions as props to the PickerModalContainer can talk to the proper PickerModal underneath and return whatever you need from that modal.

I think it is not that much of a change to be honest, just some refactoring.

ContentLicense: CC BY-SA 4.0

Body:
I have 6 dropdowns in a vehicle compare screen. Dropdowns are created with React Modal. All the data in the dropdowns are dynamic.

When the page is loaded data to be shown in the first two modals, car brands, are fetched and they are shown in modals are dropdown.

When a car brand is selected another api call is made to get the models available in that brand. This data is populated on the second dropdown.

Since there is two dropdowns for selecting model for two different brands, when one brand is selected both the model dropdowns get updated.

How can I change my code such that i can make this work and make it scalable in future if i have to add more number of cars fo comparing?

Compare.js

import React, { Component } from 'react'
import {
    View,
    StyleSheet,
    ScrollView,
    SafeAreaView,
    ActivityIndicator,
} from 'react-native';

import PickerModal from '../components/PickerModal';
import * as Api from "../api/app";

export default class CompareVehicles extends Component {
    constructor (props) {
        super(props);
        this.state = {
            isLoading: true,
            vehicleCompany: [],
            vehicleModel: [],
            vehicleSubModel: [],
        };
    }

    componentDidMount() {
        this.setState({
            isLoading: true,
        });
        this.getVehicleBrand();
    }

    getVehicleBrand = () => {
        Api.getVehicleBrands()
            .then((responseJson) => {
                console.log(responseJson);
                if (responseJson.success === true){
                    this.setState({
                        isLoading: false,
                        vehicleCompany : responseJson.data
                    });
                }  else {
                    alert("Error Loading Content")
                }
            });
    };

    submitBrand = async (data) => {
        Api.getVehicleModel(data)
            .then((responseJson) => {
                console.log(responseJson);
                if (responseJson.success === true){
                    this.setState({
                        vehicleModel: responseJson.data
                    });
                }  else {
                    alert("Error Adding Content")
                }
            });
    };

    submitModel = (data) => {
        console.log(data)
    };

    submitVariant = (data) => {
        console.log(data)
    };

    _renderPickerModal = (index) => {
        if (this.state.vehicleSubModel.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                    <PickerModal onSubmit={this.submitModel} type={'light-dropdown'} data={this.state.vehicleModel}/>
                    <PickerModal onSubmit={this.submitVariant} type={'light-dropdown'} data={this.state.vehicleSubModel}/>
                </View>
            )
        } else if(this.state.vehicleModel.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                    <PickerModal onSubmit={this.submitModel} type={'light-dropdown'} data={this.state.vehicleModel}/>
                </View>
            )
        } else if (this.state.vehicleCompany.length) {
            return (
                <View>
                    <PickerModal onSubmit={this.submitBrand} type={'light-dropdown'} data={this.state.vehicleCompany}/>
                </View>
            )
        }
    };

    render() {
        if(this.state.isLoading) {
            return (
                <SafeAreaView style={[styles.safeArea, styles.alignJustifyCenter]}>
                    <ActivityIndicator/>
                </SafeAreaView>
            );
        } else {
            return (
                <SafeAreaView style={styles.safeArea}>
                    <ScrollView
                        style={styles.scrollView}
                        scrollEventThrottle={200}
                        directionalLockEnabled={true}>
                        <View style={{flexDirection: 'row'}}>
                            <View style={{flex: 1}}>
                                {this._renderPickerModal}
                            </View>
                            <View style={{flex: 1}}>
                                {this._renderPickerModal}
                            </View>
                        </View>
                    </ScrollView>
                </SafeAreaView>
            );
        }
    }
}

const styles = StyleSheet.create({
    safeArea: {
        flex: 1,
        backgroundColor: '#ffffff',
    },
    alignJustifyCenter: {
        alignItems: 'center',
        justifyContent: 'center'
    },
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
        paddingVertical: 15,
        paddingHorizontal: 20
    }
});

PickerModal.js

import React, {Component} from 'react';
import { StyleSheet, Text, View, Modal, TouchableHighlight, TouchableOpacity, TouchableWithoutFeedback } from 'react-native';
import PropTypes from 'prop-types';
import Ionicons from 'react-native-vector-icons/Ionicons';

export default class PickerModal extends Component {
    static propTypes = {
        type: PropTypes.string.isRequired,
        data: PropTypes.array.isRequired,
        onSubmit: PropTypes.func.isRequired,
        index: PropTypes.number
    };

    constructor(props) {
        super(props);

        this.state = {
            pickerTitle: this.props.data[0].name,
            pickerValue: this.props.data[0].id,
            pickerDisplayed: false,
            index: this.props.index
        }
    }

    componentDidMount = () => {
        console.log(this.props)
    };

    submit = () => {
        const { pickerValue } = this.state;
        const { index } = this.state;
        if (pickerValue) {
            this.props.onSubmit(pickerValue, index);
        }
    };

    setPickerValue(content, index) {
        this.setState({
            pickerTitle: content.name,
            pickerValue: content.id,
            index: index
        }, () => this.submit());

        this.togglePicker();
    }

    togglePicker() {
        this.setState({
            pickerDisplayed: !this.state.pickerDisplayed
        });
    }

    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight
                    style={{width: '90%'}}
                    onPress={() => this.togglePicker()}
                    underlayColor='transparent'>
                    <View style={[styles.dropdown, this.props.type == 'dark-dropdown' ? styles.darkDropdown : styles.lightDropdown]}>
                        <Text style={[this.props.type == 'dark-dropdown' ? styles.darkDropdown : {}, {flex: 1}]}>{this.state.pickerTitle}</Text>
                        <Ionicons name={'md-arrow-dropdown'} size={25} style={[this.props.type == 'dark-dropdown' ? styles.colorWhite : {}, {marginLeft: 5, marginTop: 5}]}/>
                    </View>
                </TouchableHighlight>
                <Modal visible={this.state.pickerDisplayed} animationType={"fade"} transparent={true}>
                    <TouchableOpacity
                        activeOpacity={1}
                        style={{flex:1, justifyContent:'center', alignItems:'center', backgroundColor: 'rgba(0, 0, 0, 0.3)'}}
                        onPressOut={() => {this.togglePicker()}}>
                        <TouchableWithoutFeedback>
                            <View style={{padding: 20,
                                backgroundColor: '#ffffff',
                                bottom: 0,
                                left: 0,
                                right: 0,
                                alignItems: 'center',
                                position: 'absolute', width: '100%' }}>
                                { this.props.data.map((value, index) => {
                                    return <TouchableHighlight key={index} onPress={() => this.setPickerValue(value, this.props.index)} style={{ paddingTop: 4, paddingBottom: 4 }}>
                                        <Text style={{fontSize: 15}}>{ value.name }</Text>
                                    </TouchableHighlight>
                                })}

                                <TouchableHighlight onPress={() => this.togglePicker()} style={{ paddingTop: 50, paddingBottom: 20 }}>
                                    <Text style={{color: '#999', fontSize: 20}}>Cancel</Text>
                                </TouchableHighlight>
                            </View>
                        </TouchableWithoutFeedback>
                    </TouchableOpacity>
                </Modal>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    colorWhite: {
        color: '#fff'
    },
    darkDropdown: {
        backgroundColor: '#000',
        borderRadius: 8,
        color: '#fff'
    },
    lightDropdown: {
        borderBottomWidth: 0.3,
        borderBottomColor: '#000'
    },
    dropdown: {
        flexDirection: 'row',
        paddingHorizontal: 5,
        paddingVertical: 0,
        alignItems: 'center',
        justifyContent: 'center',
    }
});

Body:
I believe what you are doing is close enough. I'd create an intermediate ContainerComponent that should receive the brand and be completely isolated from the amount of cars that need to compare.

You just do something like:

render(){
     this.state.brandsToCompare.map(brand => <PickerModalContainer brand={brand}/>)
}

So the main Component will only be responsible for managing if the user picks 1, 2, or any amount of brands or cars they want to compare. The PickerModalContainer will have the logic for the fetching and depending on what the user selects, you just fetch and update the other PickerModals. This way you really don't care about the other Pickers, since they don't "know" each other.

If, at the end you need to get some information to compare, you can expose functions as props to the PickerModalContainer can talk to the proper PickerModal underneath and return whatever you need from that modal.

I think it is not that much of a change to be honest, just some refactoring.


问:
Converting \u003c to < character with linux tools
From an ajax call, I got back something like this:

```<code>{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.
</code>```

I' d like to convert it to a "usable" format, so \u0003c will simply be a < character.

The header of the ajax call says that this is an iso-8859-2 coding (content-type: text/plain; charset=iso-8859-2), but I' m unsure.

I tried to use iconv with many options, but no luck.

What is interesting is that for instance this site:

```<code>https://www.online-toolz.com/tools/text-unicode-entities-convertor.php
</code>```

does the trick without anything, I just can' t find out what the "from encoding" should be.

I' d be happy to use iconv.

答:
You could use the %b formatting directive of Bash's printf:

```<code>$ encoded='{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.'
$ printf -v decoded '%b\n' "$encoded"
$ printf '%s\n' "$decoded"
{"d":"<div class=\"popup_title\">BENTELER Autótechnika Kft.</div><div style=\"font-size:10pt;font-weight:bold;\">8060 Mór, Akai út 5.
</code>```

From the manual:

%b

  Causes printf to expand backslash escape sequences in the corresponding argument in the same way as echo -e (see Bash Builtins).

As Charles points out in his comment, %b as such isn't limited to Bash's printf, but required by POSIX; interpretation of \uHHHH escapes, on the other hand, only happens in Bash, as described in the escape sequences for echo.

Body:
From an ajax call, I got back something like this:

{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.

I' d like to convert it to a "usable" format, so \u0003c will simply be a < character.

The header of the ajax call says that this is an iso-8859-2 coding (content-type: text/plain; charset=iso-8859-2), but I' m unsure.

I tried to use iconv with many options, but no luck.

What is interesting is that for instance this site:

https://www.online-toolz.com/tools/text-unicode-entities-convertor.php

does the trick without anything, I just can' t find out what the "from encoding" should be.

I' d be happy to use iconv.

Body:
You could use the %b formatting directive of Bash's printf:

$ encoded='{"d":"\u003cdiv class=\"popup_title\"\u003eBENTELER Autótechnika Kft.\u003c/div\u003e\u003cdiv style=\"font-size:10pt;font-weight:bold;\"\u003e8060 Mór, Akai út 5.'
$ printf -v decoded '%b\n' "$encoded"
$ printf '%s\n' "$decoded"
{"d":"<div class=\"popup_title\">BENTELER Autótechnika Kft.</div><div style=\"font-size:10pt;font-weight:bold;\">8060 Mór, Akai út 5.

From the manual:

%b

  Causes printf to expand backslash escape sequences in the corresponding argument in the same way as echo -e (see Bash Builtins).

As Charles points out in his comment, %b as such isn't limited to Bash's printf, but required by POSIX; interpretation of \uHHHH escapes, on the other hand, only happens in Bash, as described in the escape sequences for echo.


问:
How to define integral arguments in R? (argument "a" is missing, with no default)
I am trying to recreate a python code in R, but no matter what I try I get the error message.

This is my python code which works

def Cp(T,a,b,c):
    return a+b*T+c*(T**2)
a = np.array([26.63, 20.04, 13.39])
b = np.array([0.183, 0.0945, 0.077])
c = -np.array([45.86, 30.95, 18.71])*(10**(-6))
Tp = 298
Tk = 1035
RE = np.array([0, 1, 2])
Cps1 = [(1/(Tk-Tp))*si.romberg(Cp, Tp, Tk, args=(a[i], b[i], c[i])) for  i in RE]
Cps1
```

<p>This is how I have tried to do this in R</p>

```Cp <- function(Te,a,b,c) a+b*Te+c*(Te**2)
a1 <- c(26.63, 20.04, 13.39)
b1 <- c(0.183, 0.0945, 0.077)
c1 <- -c(45.86, 30.95, 18.71)*(10**(-6))
Tp <- 298
Tk <- 1035
require(pracma)
for(i in seq(1,3,1)){
  Cps1[i] <- (1/(Tk-Tp))*integral(Cp, Tp, Tk, a=a1[i], b=b1[i], c=c1[i])
}
Cps1
```

<p>In python I get this </p>

```[126.15165675333331, 67.87464798333333, 55.55221070333332]
```

But in R I get an error:

argument "a" is missing, with no default

答:
I think this is because a = a1[i] matches the argument of integral which starts by a, namely abstol.

So a solution is to specify abstol:

```<code>integral(Cp, Tp, Tk, abstol=0, a=a1[1], b=b1[1], c=c1[1])
# 92973.77
</code>```

This matches the Python result:

```<code>> 92973.77/(Tk-Tp)
[1] 126.1517
</code>```

Explanation

There's a coding error in the pracma::integral function. This function uses match.fun in a way similar to the function I1 below:

```<code>I1 <- function(f, abstol=0, ...){
  f <- match.fun(f)
  ff <- function(x) f(x, ...)
  ff(1)
}

f <- function(x, a) x + a

I1(f, a = 2)
# Error in f(x, ...) : argument "a" is missing, with no default
</code>```

The correct way to code such a situation is to put the argument ... before the other arguments:

```<code>I2 <- function(f, ..., abstol=0){
  f <- match.fun(f)
  ff <- function(x) f(x, ...)
  ff(1)
}

f <- function(x, a) x + a

I2(f, a = 2)
# 3
</code>```

Body:
I am trying to recreate a python code in R, but no matter what I try I get the error message.

This is my python code which works

def Cp(T,a,b,c):
    return a+b*T+c*(T**2)
a = np.array([26.63, 20.04, 13.39])
b = np.array([0.183, 0.0945, 0.077])
c = -np.array([45.86, 30.95, 18.71])*(10**(-6))
Tp = 298
Tk = 1035
RE = np.array([0, 1, 2])
Cps1 = [(1/(Tk-Tp))*si.romberg(Cp, Tp, Tk, args=(a[i], b[i], c[i])) for  i in RE]
Cps1

This is how I have tried to do this in R

Cp <- function(Te,a,b,c) a+b*Te+c*(Te**2)
a1 <- c(26.63, 20.04, 13.39)
b1 <- c(0.183, 0.0945, 0.077)
c1 <- -c(45.86, 30.95, 18.71)*(10**(-6))
Tp <- 298
Tk <- 1035
require(pracma)
for(i in seq(1,3,1)){
  Cps1[i] <- (1/(Tk-Tp))*integral(Cp, Tp, Tk, a=a1[i], b=b1[i], c=c1[i])
}
Cps1

In python I get this

[126.15165675333331, 67.87464798333333, 55.55221070333332]

But in R I get an error:

argument "a" is missing, with no default

Body:
I think this is because a = a1[i] matches the argument of integral which starts by a, namely abstol.

So a solution is to specify abstol:

integral(Cp, Tp, Tk, abstol=0, a=a1[1], b=b1[1], c=c1[1])
# 92973.77

This matches the Python result:

> 92973.77/(Tk-Tp)
[1] 126.1517

Explanation

There's a coding error in the pracma::integral function. This function uses match.fun in a way similar to the function I1 below:

I1 <- function(f, abstol=0, ...){
  f <- match.fun(f)
  ff <- function(x) f(x, ...)
  ff(1)
}

f <- function(x, a) x + a

I1(f, a = 2)
# Error in f(x, ...) : argument "a" is missing, with no default

The correct way to code such a situation is to put the argument ... before the other arguments:

I2 <- function(f, ..., abstol=0){
  f <- match.fun(f)
  ff <- function(x) f(x, ...)
  ff(1)
}

f <- function(x, a) x + a

I2(f, a = 2)
# 3


问:
silverlight wcf and custom username and password
I have a silverlight application.  I have many wcf files hosted by iis 6.  I have a custom username/password store.

What is the best way to secure the wcf?

Also I will have a third party desktop app call this WCF as well.

答: Here is an example using a custom validator.</p>

ContentLicense: CC BY-SA 3.0


问:
How can I return the nth regex match in a string?
Working in PL/SQL.

I've got the following string

```<code>('Jade Court','Sarah M.', 4, '08/17/2017')
</code>```

I need to write a regex that can parse each item in between the ' characters.  So for example, I need Jade Court, Sarah M., 08/17/2017 etc.

So far, I have come up with the following regex:

```<code>(?<=')[^']+(?=')
</code>```

As you can see from the demo below, this works so far by finding each of the necessary items at the same time.

https://regex101.com/r/CV8evw/1

However, I need to be able to parse them out individually.  Is there a way to add a quantifier to my regex so that I can specify which match I want?

I tried (?<=')[^']+(?='){1} which I was hoping would return Jade Court, but unfortunately that did not work.  Is this possible?

答:
You may use the REGEXP_SUBSTR function and leverage its nth_appearance argument.

The regex you may use is

```<code>'([^']+)'
</code>```

It matches ', then captures any 1+ chars other than ' into Group 1 and then matches '. The Group 1 value can be accessed via sub_expression argument set to 1. See the regex graph:

So, to get the first match, you need to use

```<code>REGEXP_SUBSTR(col, '''([^'']+)''', 1, 1, NULL, 1)
</code>```

To extract the second one, use

```<code>REGEXP_SUBSTR(col, '''([^'']+)''', 1, 2, NULL, 1)
</code>```

And so on.

Body:
Working in PL/SQL.

I've got the following string

('Jade Court','Sarah M.', 4, '08/17/2017')

I need to write a regex that can parse each item in between the ' characters.  So for example, I need Jade Court, Sarah M., 08/17/2017 etc.

So far, I have come up with the following regex:

(?<=')[^']+(?=')

As you can see from the demo below, this works so far by finding each of the necessary items at the same time.

https://regex101.com/r/CV8evw/1

However, I need to be able to parse them out individually.  Is there a way to add a quantifier to my regex so that I can specify which match I want?

I tried (?<=')[^']+(?='){1} which I was hoping would return Jade Court, but unfortunately that did not work.  Is this possible?

Body:
You may use the REGEXP_SUBSTR function and leverage its nth_appearance argument.

The regex you may use is

'([^']+)'

It matches ', then captures any 1+ chars other than ' into Group 1 and then matches '. The Group 1 value can be accessed via sub_expression argument set to 1. See the regex graph:

So, to get the first match, you need to use

REGEXP_SUBSTR(col, '''([^'']+)''', 1, 1, NULL, 1)

To extract the second one, use

REGEXP_SUBSTR(col, '''([^'']+)''', 1, 2, NULL, 1)

And so on.


问:
Can you `= delete` a templated function on a second declaration?
Consider the following code:

```<code>template <typename T> int foo();
template <typename T> int foo() = delete;
</code>```

is this valid C++11?

GCC (9.1) says: Yes!

clang (8.0) says: No!

nvcc (9.2) says: No!

MSVC (19.20) says: Yes! (in C++14 mode, it doesn't support C++11.)

... see it all on GodBolt.

so which compilers are right and which compilers are s@#$%e ? :-)

答:
GCC and MSVC have a bug.

[dcl.fct.def.delete]

4 ... A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization...

Which I believe stands for instantiated declarations and definitions too. Since referring to a deleted function is a hard error, it must be declared as deleted asap.

Body:
Consider the following code:

template <typename T> int foo();
template <typename T> int foo() = delete;

is this valid C++11?

GCC (9.1) says: Yes!

clang (8.0) says: No!

nvcc (9.2) says: No!

MSVC (19.20) says: Yes! (in C++14 mode, it doesn't support C++11.)

... see it all on GodBolt.

so which compilers are right and which compilers are s@#$%e ? :-)


问:
Make Django-Rest-Framework API specific for the User (url/username)
My Django Backend is built up like this: We have Studyplans, that have tasks connected to them. Right now I get the studyplans via a url that looks something like this: 'url:8000/database/studyplans'.

What I want is to get the studyplans connected to the user your logged in to. So the url would look something like this: 'url:8000/database/studyplans/WilliamABC', or some other user: 'url:8000/database/studyplans/Bruce123'

Models:

```<code>from django.db import models
from datetime import date

#Create your models here.
class StudyplanTask(models.Model):
title = models.CharField(max_length=150)
description = models.CharField(max_length=1000, blank=True)
state = models.CharField(max_length=20)
doneby = models.DateField(default=date.today)

class Meta:
    verbose_name_plural = 'Tasks'

def __str__(self):
    return self.title

class StudiePlan(models.Model):
title = models.CharField(max_length=150)
description = models.CharField(max_length=1000)
tasks = models.ManyToManyField(StudyplanTask, blank=True)
doneby = models.DateField(default=date.today)

class Meta:
    verbose_name_plural = 'Studyplans'

def __str__(self):
    return self.title
</code>```

Serializers:

```<code>from rest_framework import serializers
from .models import StudiePlan, StudyplanTask

class StudyplanTaskSerializer(serializers.ModelSerializer):
class Meta:
    model = StudyplanTask
    fields = ('id', 'title', 'description', 'state', 'doneby')

class StudyplanTaskNameSerializer(serializers.ModelSerializer):
class Meta:
    model = StudyplanTask
    fields = ('id', 'title', 'description', 'state', 'doneby')

class StudyplanSerializer(serializers.ModelSerializer):
tasks = StudyplanTaskNameSerializer(many=True, read_only=True)
class Meta:
    model = StudiePlan
    fields = ('id', 'title', 'description', 'tasks', 'doneby')
</code>```

Views:

```<code>from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import StudiePlan, StudyplanTask
from .serializers import StudyplanSerializer, StudyplanTaskSerializer

# Create your views here.
class StudyplanView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = StudiePlan.objects.all()
serializer_class = StudyplanSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

class StudyplanTaskView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = StudyplanTask.objects.all()
serializer_class = StudyplanTaskSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]
</code>```

Urls:

```<code>from django.urls import path, include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('studyplans/', views.StudyplanView)
router.register('studyplan-tasks/', views.StudyplanTaskView)

urlpatterns = [
path('', include(router.urls)),
]
</code>```

API:

```<code>[
{
    "id": 1,
    "title": "Learn to Build a Mobile Frontend",
    "description": "en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad",
    "tasks": [
        {
            "id": 1,
            "title": "Learn Python",
            "description": "en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad",
            "state": "active",
            "doneby": "2019-05-31"
        }
    ],
    "doneby": "2019-05-31"
}
]
</code>```

答:
First you need to link your StudiePlan to a user

```<code>class StudiePlan(models.Model):
    title = models.CharField(max_length=150)
    description = models.CharField(max_length=1000)
    tasks = models.ManyToManyField(StudyplanTask, blank=True)
    doneby = models.DateField(default=date.today)
    user = models.ForeginKey(User, on_delete=models.CASCADE)
</code>```

Then create a view

```<code>class UserStudyplanView(StudyplanView):
    def get_queryset(self):
        return self.request.user.studieplan.all()
</code>```

And a URL

```<code>router.register('user-studyplan-tasks/', views.UserStudieplanView)
</code>```

Body:
My Django Backend is built up like this: We have Studyplans, that have tasks connected to them. Right now I get the studyplans via a url that looks something like this: 'url:8000/database/studyplans'.

What I want is to get the studyplans connected to the user your logged in to. So the url would look something like this: 'url:8000/database/studyplans/WilliamABC', or some other user: 'url:8000/database/studyplans/Bruce123'

Models:

from django.db import models
from datetime import date

#Create your models here.
class StudyplanTask(models.Model):
title = models.CharField(max_length=150)
description = models.CharField(max_length=1000, blank=True)
state = models.CharField(max_length=20)
doneby = models.DateField(default=date.today)

class Meta:
    verbose_name_plural = 'Tasks'

def __str__(self):
    return self.title

class StudiePlan(models.Model):
title = models.CharField(max_length=150)
description = models.CharField(max_length=1000)
tasks = models.ManyToManyField(StudyplanTask, blank=True)
doneby = models.DateField(default=date.today)

class Meta:
    verbose_name_plural = 'Studyplans'

def __str__(self):
    return self.title

Serializers:

from rest_framework import serializers
from .models import StudiePlan, StudyplanTask

class StudyplanTaskSerializer(serializers.ModelSerializer):
class Meta:
    model = StudyplanTask
    fields = ('id', 'title', 'description', 'state', 'doneby')

class StudyplanTaskNameSerializer(serializers.ModelSerializer):
class Meta:
    model = StudyplanTask
    fields = ('id', 'title', 'description', 'state', 'doneby')

class StudyplanSerializer(serializers.ModelSerializer):
tasks = StudyplanTaskNameSerializer(many=True, read_only=True)
class Meta:
    model = StudiePlan
    fields = ('id', 'title', 'description', 'tasks', 'doneby')

Views:

from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import StudiePlan, StudyplanTask
from .serializers import StudyplanSerializer, StudyplanTaskSerializer

# Create your views here.
class StudyplanView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = StudiePlan.objects.all()
serializer_class = StudyplanSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

class StudyplanTaskView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = StudyplanTask.objects.all()
serializer_class = StudyplanTaskSerializer

#get
def get(self, request):
    hello_param = request.GET["helloParam"]
#post
def post(self, request):
    hello_param = request.POST["helloParam"]
#put
def put(self, request):
    hello_param = request.PUT["helloParam"]
#patch
def patch(self, request):
    hello_param = request.PATCH["helloParam"]
#delete
def delete(self, request):
    hello_param = request.DELETE["helloParam"]

Urls:

from django.urls import path, include
from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register('studyplans/', views.StudyplanView)
router.register('studyplan-tasks/', views.StudyplanTaskView)

urlpatterns = [
path('', include(router.urls)),
]

API:

[
{
    "id": 1,
    "title": "Learn to Build a Mobile Frontend",
    "description": "en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad",
    "tasks": [
        {
            "id": 1,
            "title": "Learn Python",
            "description": "en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad en opresesntion som är bra dokumenterad",
            "state": "active",
            "doneby": "2019-05-31"
        }
    ],
    "doneby": "2019-05-31"
}
]

Body:
First you need to link your StudiePlan to a user

class StudiePlan(models.Model):
    title = models.CharField(max_length=150)
    description = models.CharField(max_length=1000)
    tasks = models.ManyToManyField(StudyplanTask, blank=True)
    doneby = models.DateField(default=date.today)
    user = models.ForeginKey(User, on_delete=models.CASCADE)

Then create a view

class UserStudyplanView(StudyplanView):
    def get_queryset(self):
        return self.request.user.studieplan.all()

And a URL

router.register('user-studyplan-tasks/', views.UserStudieplanView)


问:
Action changes state of all values instead of just particular ones
I am trying to rewrite my application (weather check application) from standard React state approach into Redux based one. I encountered problem with changing state. In pure React by lanuching this.setState() I was changing only the piece I was passing as an argument in this method. In Redux it seems to change the entire state object even though I pass only part of the entire state, but probably I am doing something wrong.

Here you can see how state transforms when I trigger my action:

In my example I am trying to set coordinates states (lattitude and longtitude) when clicking the button. Tried several things - I thought that perhaps passing state = [] in reducer function clears out the entire state but I cannot get rid of it as application crashes.

I have 3 reducers: first for geolocation coords, second for weather details and last one for handling loading spinner to be displayed or not

```<code>const reducers = combineReducers({
    weather: weatherReducer,
    coords: coordsReducer,
    loading: loadingReducer
})
</code>```

Then I have store with initial states as following:

```<code>const store = createStore(reducers, {
    weather: [{ temperature: "", humidity: "", windSpeed: "", pressure: "", pollution: "", date: "" }],
    coords: { lat: null, lng: null },
    loading: { loading: false }
}, allStoreEnhancers);
</code>```

Not sure if splitting them all into 3 parts is good but I believe so (feel free to point out if I am wrong)

coordsReducer.js:

```<code>export default function weatherReducer(state = [], { type, payload }) {
    switch (type) {
        case 'updateCoords':
            return payload
        case 'clearCoords':
            return payload
        default:
            return state
    }
}
</code>```

and coordsActions.js (simply set coords or clear them out)

```<code>export function updateCoords(lat = 0, lng = 0) {
    return {
        type: 'updateCoords',
        payload: {
            lat: lat,
            lng: lng
        }
    }
}

export function clearCoords() {
    return {
        type: 'clearCoords',
        payload: {
            lat: null,
            lng: null
        }
    }
}
</code>```

Basically I need few things:
1. Opinion if the way I splitted my state and action and reducers makes sense
2. How to change state of single properties instead of changing entire state object?

答:
This is because you have to pass in the previous state when you are setting new properties. You can do this easily with the spread operator. </p>

```<code>export default function weatherReducer(state = [], { type, payload }) {
    switch (type) {
        case 'updateCoords':
           return {
            ...state,
            lat: payload.lat,
            lng: payload. lng
         }
        case 'clearCoords':
            return {
             ...state,
            lat: null,
            lng: null
         }
        default:
            return state
    }
}
</code>```

<p>and you can set the values you want to update individually. </p>

Body:
I am trying to rewrite my application (weather check application) from standard React state approach into Redux based one. I encountered problem with changing state. In pure React by lanuching this.setState() I was changing only the piece I was passing as an argument in this method. In Redux it seems to change the entire state object even though I pass only part of the entire state, but probably I am doing something wrong.

Here you can see how state transforms when I trigger my action:

In my example I am trying to set coordinates states (lattitude and longtitude) when clicking the button. Tried several things - I thought that perhaps passing state = [] in reducer function clears out the entire state but I cannot get rid of it as application crashes.

I have 3 reducers: first for geolocation coords, second for weather details and last one for handling loading spinner to be displayed or not

const reducers = combineReducers({
    weather: weatherReducer,
    coords: coordsReducer,
    loading: loadingReducer
})

Then I have store with initial states as following:

const store = createStore(reducers, {
    weather: [{ temperature: "", humidity: "", windSpeed: "", pressure: "", pollution: "", date: "" }],
    coords: { lat: null, lng: null },
    loading: { loading: false }
}, allStoreEnhancers);

Not sure if splitting them all into 3 parts is good but I believe so (feel free to point out if I am wrong)

coordsReducer.js:

export default function weatherReducer(state = [], { type, payload }) {
    switch (type) {
        case 'updateCoords':
            return payload
        case 'clearCoords':
            return payload
        default:
            return state
    }
}

and coordsActions.js (simply set coords or clear them out)

export function updateCoords(lat = 0, lng = 0) {
    return {
        type: 'updateCoords',
        payload: {
            lat: lat,
            lng: lng
        }
    }
}

export function clearCoords() {
    return {
        type: 'clearCoords',
        payload: {
            lat: null,
            lng: null
        }
    }
}

Basically I need few things:
1. Opinion if the way I splitted my state and action and reducers makes sense
2. How to change state of single properties instead of changing entire state object?

Body:
This is because you have to pass in the previous state when you are setting new properties. You can do this easily with the spread operator.

export default function weatherReducer(state = [], { type, payload }) {
    switch (type) {
        case 'updateCoords':
           return {
            ...state,
            lat: payload.lat,
            lng: payload. lng
         }
        case 'clearCoords':
            return {
             ...state,
            lat: null,
            lng: null
         }
        default:
            return state
    }
}

and you can set the values you want to update individually.


问:
Excel macro disabled warning not showing
Excel security warning, that macros has been disabled stop showing on the start of excel.

Only way I can allow it now is on ribbon "File" where is warning that some content has been disabled.

How can I get it back so it will show on the start of Excel? It stopped working couple weeks ago and it stopped for all people in the office. My private office works normaly. Both Excels are 365.

答: You can change this setting in File/Options/Trust Center/Trust Center Settings/Macro Settings -> Mark 'Disable all macros with notification'. Note that this setting might be locked by your system administrator.


问:
Functions in Haskell
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

```<code>fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)
</code>```

This gives me a syntax error :-S

```<code>ERROR - Syntax error in input (unexpected `=')
</code>```

答:
It should be mentioned that the most elegant way to write this function is:

```<code>fac n = product [1..n]
</code>```

See http://www.willamette.edu/~fruehr/haskell/evolution.html for details.

Title: Functions in Haskell

Body:
I'm new to functional programming. I have a basic question.

I'm using the Hugs interpreter,

I would like to write a function in Haskell; I went though several tutorials, but I'm not getting it.

fact :: Int -> Int
fact n = if n == 0 then
1
else
n * fact (n-1)

This gives me a syntax error :-S

ERROR - Syntax error in input (unexpected `=')

Body:
It should be mentioned that the most elegant way to write this function is:

fac n = product [1..n]

See http://www.willamette.edu/~fruehr/haskell/evolution.html for details.


问:
Python: replacing outliers values with median values
I have a python data-frame in which there are some outlier values. I would like to replace them with the median values of the data, had those values not been there.

```<code>id         Age
10236    766105
11993       288
9337        205
38189        88
35555        82
39443        75
10762        74
33847        72
21194        70
39450        70
</code>```

So, I want to replace all the values > 75 with the median value of the dataset of the remaining dataset, i.e., the median value of 70,70,72,74,75.

I'm trying to do the following:

Replace with 0, all the values that are greater than 75

Replace the 0s with median value.

But somehow, the below code not working

```<code>df['age'].replace(df.age>75,0,inplace=True)
</code>```

答:
A more general solution I've tried lately: replace 75 with the median of the whole column and then follow a solution similar to what Bharath suggested:</p>

```<code>median = float(df['Age'].median())
df["Age"] = np.where(df["Age"] > median, median, df['Age'])
</code>```

Body:
I have a python data-frame in which there are some outlier values. I would like to replace them with the median values of the data, had those values not been there.

id         Age
10236    766105
11993       288
9337        205
38189        88
35555        82
39443        75
10762        74
33847        72
21194        70
39450        70

So, I want to replace all the values > 75 with the median value of the dataset of the remaining dataset, i.e., the median value of 70,70,72,74,75.

I'm trying to do the following:

Replace with 0, all the values that are greater than 75

Replace the 0s with median value.

But somehow, the below code not working

df['age'].replace(df.age>75,0,inplace=True)

Body:
A more general solution I've tried lately: replace 75 with the median of the whole column and then follow a solution similar to what Bharath suggested:

median = float(df['Age'].median())
df["Age"] = np.where(df["Age"] > median, median, df['Age'])


问:
Sort from low to high the two dimensional int arrays according to the sum of arr[i]
I've got to a dead end in the homework working on sorting a integers two-dimensional array.

The instructions are to create a function that takes a two-dimensional int array
(not necessarily a matrix) and sort the Outer array according to the sum of the inner arrays. in other words, in the first index of the array should be the inner array with the lowest sum.

Example -
input - int[][] array = {{2, 4, 1,9,9,9,9}, {6, 8}, {7, 3, 6, 5, 1}};

output - array = {{6, 8}, {7, 3, 6, 5, 1}, {2, 4, 1,9,9,9,9}};

My logic so far is creating a new one dimensional array that will include the sum
of each of the inner arrays from the main array.
and work with the sorting according to it.

```<code>public static int[] arraysCalculator(int[][] arr) {
int[] sums = new int[arr.length];
int sum= 0;
for(int i = 0; i  < arr.length; i++)
{
    for(int j = 0; j < arr[i].length; j++)
    {
        sum += arr[i][j];
    }
    sums[i] = sum;
    sum = 0;
}
</code>```

答:
You can easily sum an int[] by streaming it and then calling sum(). From there, it's just a matter of calling Arrays.sort with a comparator that compares this sum:

```<code>Arrays.sort(array, Comparator.comparingInt(a -> Arrays.stream(a).sum()));
</code>```

Body:
I've got to a dead end in the homework working on sorting a integers two-dimensional array.

The instructions are to create a function that takes a two-dimensional int array
(not necessarily a matrix) and sort the Outer array according to the sum of the inner arrays. in other words, in the first index of the array should be the inner array with the lowest sum.

Example -
input - int[][] array = {{2, 4, 1,9,9,9,9}, {6, 8}, {7, 3, 6, 5, 1}};

output - array = {{6, 8}, {7, 3, 6, 5, 1}, {2, 4, 1,9,9,9,9}};

My logic so far is creating a new one dimensional array that will include the sum
of each of the inner arrays from the main array.
and work with the sorting according to it.

public static int[] arraysCalculator(int[][] arr) {
int[] sums = new int[arr.length];
int sum= 0;
for(int i = 0; i  < arr.length; i++)
{
    for(int j = 0; j < arr[i].length; j++)
    {
        sum += arr[i][j];
    }
    sums[i] = sum;
    sum = 0;
}

Body:
You can easily sum an int[] by streaming it and then calling sum(). From there, it's just a matter of calling Arrays.sort with a comparator that compares this sum:

Arrays.sort(array, Comparator.comparingInt(a -> Arrays.stream(a).sum()));


答:
You got like one third. What you need now:

after creating that first array sums that contains the sums of the "inner" arrays, you simply create an exact copy of that array, like originalSums

then, you sort the content of sums

Example: say sums and originalSums are [ 12, 3, 7]. After sorting you get:

originalSums: [ 12, 3, 7]

sums: [ 3, 7, 12]

The thing is: by looking at both arrays, you can decide how to swap the inner arrays to match the order that sums shows you now.

In the above example, you notice that 12 has the original index 0. After sorting, its index is 2. So you know that you have to "swap" the inner arrays for 0 and 2. You can also deduce that 3 should go to index 0, and 7 to index 2.

Of course, it is still a bit of work to ensure that the swapping works out (like you better not swap any index twice).

The most basic way to get the whole thing going is to simply look at just one index at a time (like you do some sort of bubble sort).

Long story short: there are many different ways to solve this. I suggest you start with the easiest path.

Title: Sort from low to high the two dimensional int arrays according to the sum of arr[i]


问:
The remove() function is deleting every element I clicked instead of the one recently clicked
I am creating a gallery web app just for fun. I am adding context menu to manipulate images. I added the functionality to delete a certain image by right clicking on it but when a right click on multiple images and click on delete option once, all the previously clicked images also gets removed.

The delete option should delete the recently clicked image only.

$(".image").on("mousedown", function(event) {
  var i = $(this);
  var c = $(".context");
  c.css("display", "none");

  if (event.which == 3) {
    c.css({
      "top": event.pageY + "px",
      "left": event.pageX + "px"
    }).slideDown();

    $("#delete").on("click", function() {
      var p = i.offset();
      i.next().css("margin-left", "290px");
      i.css({
        "position": "absolute",
        "top": p.top - 72,
        "left": p.left - 10
      });

      i.animate({
        top: "-50%",
        opacity: "0"
      });

      setTimeout(function() {
        i.next().animate({
          "marginLeft": "10px"
        });
        i.prev().animate({
          "marginRight": "10px"
        });
        i.remove();
      }, 200);

      c.css("display", "none");
    });
  } else if (event.which == 1 || event.which == 2) {
    c.css("display", "none");
  }
});
```

答:
It's because .on attaches the click event handler to the delete button without overriding the last event.

So each right click, which I believe right click is the contextmenu event, it's adding on to the attached events.

When delete is pressed, all of the attached events get fired.

You need to use .click() or use .unbind('click'), to unbind the last event first.


问:
HTML has a margin bigger than body
I'm creating my own personal site using bootstrap.

I've using bootstrap4 with some modifications. However the html margin is bigger than body.

I've already checked other questions and they say that
 or some other tag has a default margin and you need to zero that, however I'm using a reset.css and plus I tried to zero margin of a lot of elements and it didn't work.

the reset css and the link to my web site: https://sitezinho--mateusmsouza.repl.co/

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}
```

<p>and HTML</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
    <title>Mateus Machado - Site Pessoal</title>
    <link rel="stylesheet" type="text/css" href="public/css/reset.css">
    <link rel="stylesheet" type="text/css" href="public/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="public/css/custom.css">

    <script type="text/javascript" href="public/js/jquery-3.4.0.min.js">

    </script>
    <script type="text/javascript" src='public/js/bootstrap.bundle.min.js'>

    </script>
</head>

<body>
    <main role="main">
        <nav class="navbar sticky-top navbar-expand-lg navbar-light " style="background-color: black">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item active">Hello World</li>
                <li class="nav-item active">Projetos</li>
                <li class="nav-item active">Material de Estudo</li>

            </ul>

            <ul class="navbar-nav mr-auto>
          <li class=" nav-item active "> <img src="GitHub-Mark-Light-32px.png "> </li>
        </ul>

      </nav>

    <section class="my-4 " >
      <div class="content ">
        <h1 class="h1-responsive font-weight-bold text-center ">printf("Olar ");</h1>

        <p class="lead grey-text text-center w-responsive mx-auto mb-5 ">Me chamo Mateus Machado, trabalho atualmente como Software Tester, graduando em Tecnologia de Banco de Dados. Desenvolvo para projetos pessoais no tempo livre e no tempo mais livre toco violão e faço outras coisas de humano :)</p>

        <div class="container-fluid px-5 py-5 " style="background-color:grey ";>
          <div class="row container-fluid " ">
                <div class="col-5">
                    <img class="img-fluid img-thumbnail" src="img/magogenteboa.jpg">
            </div>

            <div class="col-7 container-fluid">
              <ul>
                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_school2.png">
                   <p class="text-light">Técnico em Redes de Computadores pela
                     Etec Cônego José Bentos
                    </p>
                  <small class="text-light font-italic">Período: 2016 - 2017</small>

                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_school2.png">
                  <p class="text-light">Graduando em Tecnologia de Banco de Dados pela Fatec São José dos Campos </p>
                  <small class="text-light font-italic">Período: 2018 - Atualmente</small>
                </li>

                <li style="background-color:rgba(0,0,0,.3)" class="px-3 py-3 my-1">
                  <img class="img-fluid" src="img/baseline_work2.png">
                  <p class="text-light">Tester de Software na
                    DeMaria
                  </p>
                  <small class="text-light font-italic" >Período: 2017 - Atualmente</small>
                </li>
              </ul>

            </div>
          </div>
        </div>
      </div>

    </section>
    </main>
                <style>
              body, p, html , h1, nav, section, main, img{
                margin: 0;

              }
            </style>
  </body>
</html>
</code>```

答:
Change margin: 0; to margin: 0 !important;

This may fix it, but the correct way would be removing 'margin' from the class that is being applied to this element.

Title: HTML has a margin bigger than body

Body:
I'm creating my own personal site using bootstrap.

I've using bootstrap4 with some modifications. However the html margin is bigger than body.

I've already checked other questions and they say that
 or some other tag has a default margin and you need to zero that, however I'm using a reset.css and plus I tried to zero margin of a lot of elements and it didn't work.

the reset css and the link to my web site: https://sitezinho--mateusmsouza.repl.co/

/* http://meyerweb.com/eric/tools/css/reset/
   v2.0 | 20110126
   License: none (public domain)
*/

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

and HTML

<!DOCTYPE html>

    <title>Mateus Machado - Site Pessoal</title>
    <link rel="stylesheet" type="text/css" href="public/css/reset.css">
    <link rel="stylesheet" type="text/css" href="public/css/bootstrap.min.css">
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="public/css/custom.css">

Hello World

Projetos

Material de Estudo

printf("Olar ");

Me chamo Mateus Machado, trabalho atualmente como Software Tester, graduando em Tecnologia de Banco de Dados. Desenvolvo para projetos pessoais no tempo livre e no tempo mais livre toco violão e faço outras coisas de humano :)

Técnico em Redes de Computadores pela
                     Etec Cônego José Bentos

                  Período: 2016 - 2017

Graduando em Tecnologia de Banco de Dados pela Fatec São José dos Campos

                  Período: 2018 - Atualmente

Tester de Software na
                    DeMaria

                  Período: 2017 - Atualmente


问:
RegEx for finding matches between quotes
Here i am trying to find String within double quotes .

```<code>   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.
</code>```

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

答:
You can do a CSV style hybrid using your Java code, but the regex has to be changed.

Java

```<code>import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{

    public static List<String> getList(String value)
    {
        String regex = "(?:(?:^|,|\\r?\\n)\\s*)(?:(?:(\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\"|“[^“”\\\\]*(?:\\\\[\\S\\s][^“”\\\\]*)*”))(?:\\s*(?:(?=,|\\r?\\n)|$))|([^,]*)(?:\\s*(?:(?=,)|$)))";
        List<String> allMatches = new ArrayList<String>();
        if ( value.length() > 0  )
        {
            Matcher m = Pattern.compile( regex ).matcher( value );
            while ( m.find() ) {
                String str = m.group(2);
                if ( str == null ) {
                    str = m.group(1);
                    str = str.replaceAll( "^[\"“”]|[\"“”]$", "" );
                }
                allMatches.add(str.trim());
            }
        }
        return allMatches;
    }

    public static  void main (String[] args) throws java.lang.Exception
    {
        List<String>  result = getList("400,test,\"QT_don't split, this_QT\",15");
        System.out.println( result );

        result = getList("500,test,“LQT_don't split, this_RQT”,15");
        System.out.println( result );

        result = getList("600,test,\"QT_don't split, this_QT\",15");
        System.out.println( result );

    }
}
</code>```

https://ideone.com/b8Wnz9

Output

```<code>[400, test, QT_don't split, this_QT, 15]
[500, test, LQT_don't split, this_RQT, 15]
[600, test, QT_don't split, this_QT, 15]
</code>```

Regex Expanded

```<code> (?:
      (?: ^ | , | \r? \n )          # Delimiter comma or newline
      \s*                           # leading optional whitespaces
 )
 (?:                           # Double Quoted field
      (?:
           "                             # Quoted string field ""
           (                             # (1), double quoted string data
                [^"\\]*
                (?: \\ [\S\s] [^"\\]* )*
           )
           "

        |                              # or

           “                             # Quoted string field Left/right double quotes “”
           (                             # (2), double quoted string data
                [^“”\\]*
                (?: \\ [\S\s] [^“”\\]* )*
           )
           ”
      )
      (?:
           \s*                           # trailing optional whitespaces
           (?:
                (?= , | \r? \n )              # Delimiter ahead, comma or newline
             |  $
           )
      )
   |                              # OR
      ( [^,]* )                     # (3), Non quoted field
      (?:
           \s*                           # trailing optional whitespaces
           (?:
                (?= , )                       # Delimiter ahead, comma
             |  $
           )
      )
 )
</code>```

Body:
Here i am trying to find String within double quotes .

   List<String> getList(String value){
    String regex = "\"[^\"]*\"|[^,]+";
    List<String> allMatches = new ArrayList<String>();
    if (StringUtils.isNotBlank(value)) {
        Matcher m = Pattern.compile(regex).matcher(value);
        while (m.find() && StringUtils.isNotBlank(m.group())) {
            String str=m.group().replaceAll("^\"|\"$", "");
            allMatches.add(str.trim());
        }
    }
    return allMatches;
  }

  result = getList(400,test,\"don't split, this\",15);
  result have [400,test,don't split, this,15] all comma seperated string except inside quotes.

It is working well for pattern "" but not for “” .  "foo,bar", is different than "foo,bar"  here is not working regex

Body:
You can do a CSV style hybrid using your Java code, but the regex has to be changed.

Java

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{

    public static List<String> getList(String value)
    {
        String regex = "(?:(?:^|,|\\r?\\n)\\s*)(?:(?:(\"[^\"\\\\]*(?:\\\\[\\S\\s][^\"\\\\]*)*\"|“[^“”\\\\]*(?:\\\\[\\S\\s][^“”\\\\]*)*”))(?:\\s*(?:(?=,|\\r?\\n)|$))|([^,]*)(?:\\s*(?:(?=,)|$)))";
        List<String> allMatches = new ArrayList<String>();
        if ( value.length() > 0  )
        {
            Matcher m = Pattern.compile( regex ).matcher( value );
            while ( m.find() ) {
                String str = m.group(2);
                if ( str == null ) {
                    str = m.group(1);
                    str = str.replaceAll( "^[\"“”]|[\"“”]$", "" );
                }
                allMatches.add(str.trim());
            }
        }
        return allMatches;
    }

    public static  void main (String[] args) throws java.lang.Exception
    {
        List<String>  result = getList("400,test,\"QT_don't split, this_QT\",15");
        System.out.println( result );

        result = getList("500,test,“LQT_don't split, this_RQT”,15");
        System.out.println( result );

        result = getList("600,test,\"QT_don't split, this_QT\",15");
        System.out.println( result );

    }
}

https://ideone.com/b8Wnz9

Output

[400, test, QT_don't split, this_QT, 15]
[500, test, LQT_don't split, this_RQT, 15]
[600, test, QT_don't split, this_QT, 15]

Regex Expanded

 (?:
      (?: ^ | , | \r? \n )          # Delimiter comma or newline
      \s*                           # leading optional whitespaces
 )
 (?:                           # Double Quoted field
      (?:
           "                             # Quoted string field ""
           (                             # (1), double quoted string data
                [^"\\]*
                (?: \\ [\S\s] [^"\\]* )*
           )
           "

        |                              # or

           “                             # Quoted string field Left/right double quotes “”
           (                             # (2), double quoted string data
                [^“”\\]*
                (?: \\ [\S\s] [^“”\\]* )*
           )
           ”
      )
      (?:
           \s*                           # trailing optional whitespaces
           (?:
                (?= , | \r? \n )              # Delimiter ahead, comma or newline
             |  $
           )
      )
   |                              # OR
      ( [^,]* )                     # (3), Non quoted field
      (?:
           \s*                           # trailing optional whitespaces
           (?:
                (?= , )                       # Delimiter ahead, comma
             |  $
           )
      )
 )


问:
How to delete from multiple tables in one DELETE statement in a .cfc file?
I have two tables. A device table and a location table. There can only be one device in the device table but there can be multiple devices with multiple locations in the location table.

If a user deletes a device, I need to also delete the locations with the same id from the location table.

Is there a way to delete from multiple tables in a Delete statement (using sql server) from within a cfc page?

I have tried to write a <cfif> when I do my initial delete, to check if there were records deleted and if so, run the next delete statement that deletes the devices from the table.

I have also tried to use this format.

```<code>delete T1, T2
from T1
inner join T2 on T1.device_id = T2.device_id
where T2.device_id = '111';
</code>```

T1 = device table, T2 = Location table

```<code><cfif ARGUMENTS.submitButton eq 'btn_Delete'>
   <cfquery name="DeleteDevice" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device
        WHERE device_id = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
    </cfquery>
 </cfif>

<cfif DeleteDevice.RecordCount eq 1>
<cfquery name="DeleteLocation" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device_location_xref
        WHERE device_location_xref_recno=<cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>
</code>```

答:
(I thought it would be helpful to consolidate all of the useful comments under a Community wiki answer)

Can you DELETE from multiple tables in a single statement?

Not with SQL Server, no. Some databases, like MySQL, support multi-table delete statements. SQL Server does not. You'll need multiple delete statements. However, if the goal is simply to delete the records, it makes little difference.

What's wrong with the current code?

There are several reasons the current code isn't working. First, the initial delete query only executes IF the form was submitted. The second code block references that same query, but doesn't verify it actually exists first. That'll cause an undefined variable error if the form wasn't submitted yet.

Second, and more importantly, DELETE statements never return a "query" object, in CF parlance. So even if the first query did execute, the query variable DeleteDevice will never exist. Again, resulting in an undefined variable error when the code tries to use it here: <cfif DeleteDevice.RecordCount eq 1>.

Though unless there's more to it,... that cfif serves little purpose IMO. If records exist for a deviceID, they'll be deleted. If not, nothing will happen. Any negligible savings of skipping the second delete is outweighed by the added code complexity.

Lastly, though it doesn't cause a hard error, maxRows=1 isn't doing what you're thinking. It has no affect whatsoever on DELETE statements and won't prevent a DELETE statement from removing multiple records. The maxRows attribute only applies to statements that return a "query" object, and is used limit the number of records contained in that query.

Then how can I handle multiple delete statements?

Since SQL Server doesn't support multi-table DELETE statements, you'll need two statements - no matter what. There are several ways to structure the SQL, each with their own pros and cons. However, in all cases you should use a transaction to group the related statements and ensure everything completes or fails as a single unit

Multiple cfquery's

Just run your two queries, one after the other, inside a transaction. Though do swap the statement order, as Shawn suggested. Due to the possibility of FK constraints, it's just a good practice to delete from child/FK tables first and the primary/PK table last.

<cftransaction>
      <cfquery datasource="#session.dsn#">
         DELETE FROM device_location_xref WHERE ...
      </cfquery>
      <cfquery datasource="#session.dsn#">
        DELETE FROM device  WHERE .....
      </cfquery>
</cftransaction>

Multiple statements within a single cfquery

As JamesAMohler's answer demonstrates, placing both SQL statements within a single cfquery tag is another option. However, keep in mind the limitations Alex mentioned. Multiple statements can be disabled at the db/driver level, for security reasons. So this approach may not work in all environments.

<cftransaction>
      <cfquery datasource="#session.dsn#">
         DELETE FROM device_location_xref WHERE ...
         DELETE FROM device  WHERE .....
      </cfquery>
   </cftransaction>

SQL Stored procedure

Another option is what Shawn suggested: put the sql logic into a stored procedure. Generally speaking, stored procedures are better suited for complex sql operations, and unlike cfquery, they can return multiple result sets.

```<code>CREATE PROCEDURE DeleteDevice
  @deviceID VARCHAR(50)
AS
BEGIN
    -- minimal error handling for demo only
    BEGIN TRAN
        DELETE FROM device_location_xref
        WHERE device_location_xref_recno = @deviceID

        DELETE from device
        WHERE device_id = @deviceID

    END TRAN

END
</code>```

Then invoke it with cfstoredproc instead of cfquery.

```<code><cfstoredproc procedure="DeleteDevice" datasource="#ds#">
   <cfprocparam type="in" value="#formStruct.deviceId#"
          cfsqltype="cf_sql_varchar">
</cfstoredproc>
</code>```

Soft vs Hard Deletes

Lastly, an alternative Shawn mentioned is a "soft-delete". Instead of physically removing the records, you could add a BIT column to the table(s). Then UPDATE that column flag whenever you need to mark a record as deleted. See this thread for a discussion of the pros and cons of soft-deletes.

```<code>      UPDATE TableName
      SET    IsDeleted   = 1
      WHERE  TheIDColumn = 12345
</code>```

Body:
I have two tables. A device table and a location table. There can only be one device in the device table but there can be multiple devices with multiple locations in the location table.

If a user deletes a device, I need to also delete the locations with the same id from the location table.

Is there a way to delete from multiple tables in a Delete statement (using sql server) from within a cfc page?

I have tried to write a <cfif> when I do my initial delete, to check if there were records deleted and if so, run the next delete statement that deletes the devices from the table.

I have also tried to use this format.

delete T1, T2
from T1
inner join T2 on T1.device_id = T2.device_id
where T2.device_id = '111';

T1 = device table, T2 = Location table

<cfif ARGUMENTS.submitButton eq 'btn_Delete'>
   <cfquery name="DeleteDevice" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device
        WHERE device_id = <cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
    </cfquery>
 </cfif>

<cfif DeleteDevice.RecordCount eq 1>
<cfquery name="DeleteLocation" datasource="#session.dsn#" maxRows=1 >
        DELETE from #session.tq#device_location_xref
        WHERE device_location_xref_recno=<cfqueryparam value="#formStruct.deviceId#" cfsqltype="CF_SQL_VARCHAR">
</cfquery>

Body:
(I thought it would be helpful to consolidate all of the useful comments under a Community wiki answer)

Can you DELETE from multiple tables in a single statement?

Not with SQL Server, no. Some databases, like MySQL, support multi-table delete statements. SQL Server does not. You'll need multiple delete statements. However, if the goal is simply to delete the records, it makes little difference.

What's wrong with the current code?

There are several reasons the current code isn't working. First, the initial delete query only executes IF the form was submitted. The second code block references that same query, but doesn't verify it actually exists first. That'll cause an undefined variable error if the form wasn't submitted yet.

Second, and more importantly, DELETE statements never return a "query" object, in CF parlance. So even if the first query did execute, the query variable DeleteDevice will never exist. Again, resulting in an undefined variable error when the code tries to use it here: <cfif DeleteDevice.RecordCount eq 1>.

Though unless there's more to it,... that cfif serves little purpose IMO. If records exist for a deviceID, they'll be deleted. If not, nothing will happen. Any negligible savings of skipping the second delete is outweighed by the added code complexity.

Lastly, though it doesn't cause a hard error, maxRows=1 isn't doing what you're thinking. It has no affect whatsoever on DELETE statements and won't prevent a DELETE statement from removing multiple records. The maxRows attribute only applies to statements that return a "query" object, and is used limit the number of records contained in that query.

Then how can I handle multiple delete statements?

Since SQL Server doesn't support multi-table DELETE statements, you'll need two statements - no matter what. There are several ways to structure the SQL, each with their own pros and cons. However, in all cases you should use a transaction to group the related statements and ensure everything completes or fails as a single unit

Multiple cfquery's

Just run your two queries, one after the other, inside a transaction. Though do swap the statement order, as Shawn suggested. Due to the possibility of FK constraints, it's just a good practice to delete from child/FK tables first and the primary/PK table last.

<cftransaction>
      <cfquery datasource="#session.dsn#">
         DELETE FROM device_location_xref WHERE ...
      </cfquery>
      <cfquery datasource="#session.dsn#">
        DELETE FROM device  WHERE .....
      </cfquery>
</cftransaction>

Multiple statements within a single cfquery

As JamesAMohler's answer demonstrates, placing both SQL statements within a single cfquery tag is another option. However, keep in mind the limitations Alex mentioned. Multiple statements can be disabled at the db/driver level, for security reasons. So this approach may not work in all environments.

<cftransaction>
      <cfquery datasource="#session.dsn#">
         DELETE FROM device_location_xref WHERE ...
         DELETE FROM device  WHERE .....
      </cfquery>
   </cftransaction>

SQL Stored procedure

Another option is what Shawn suggested: put the sql logic into a stored procedure. Generally speaking, stored procedures are better suited for complex sql operations, and unlike cfquery, they can return multiple result sets.

CREATE PROCEDURE DeleteDevice
  @deviceID VARCHAR(50)
AS
BEGIN
    -- minimal error handling for demo only
    BEGIN TRAN
        DELETE FROM device_location_xref
        WHERE device_location_xref_recno = @deviceID

        DELETE from device
        WHERE device_id = @deviceID

    END TRAN

END

Then invoke it with cfstoredproc instead of cfquery.

<cfstoredproc procedure="DeleteDevice" datasource="#ds#">
   <cfprocparam type="in" value="#formStruct.deviceId#"
          cfsqltype="cf_sql_varchar">
</cfstoredproc>

Soft vs Hard Deletes

Lastly, an alternative Shawn mentioned is a "soft-delete". Instead of physically removing the records, you could add a BIT column to the table(s). Then UPDATE that column flag whenever you need to mark a record as deleted. See this thread for a discussion of the pros and cons of soft-deletes.

      UPDATE TableName
      SET    IsDeleted   = 1
      WHERE  TheIDColumn = 12345


问:
can not send array inside formData with Axios
I am working on a project with vuejs and to handle my AJAX requests I use Axios, the problem is I can not send array inside my formData, I see [object] on my request in network tab of developers panel.  Is it possible to pass as a parameter to a POST request with an array of objects inside main object, of this type: inside my object I have an array with lenght 2 as below

```<code>  (3) [{…}, {…}, {…}, __ob__: Observer]
  0:
  created_at: "2018-12-16 18:37:00"
  id: 1
  properties: Array(8)
  0: {…}
  1: {…}
  2: {…}
  3: {…}
  4: {…}
  5: {…}
  6: {…}
  7: {…}
  title: "Building properties"
  updated_at: "2018-12-16 18:37:00"
 __proto__: Object
 1: {…}
 2: {…}
</code>```

I tried JSON.stringy both for array and whole object but I get 405 method not allowed. I also tried adding config. I see some solution as paramsSerializer but can not understand where I should write it exactly.

```<code>   var data = {
    user_id: this.user_info,
    type_id: this.dorm_type,
    city_id: this.city,
    district_id: this.district,
    is_active: this.is_active,
    name: this.name,
    slug: this.slug,
    keywords: this.keywords,
    description: this.description,
    member: this.member,
    capacity: this.capacity,
    is_wifi: this.is_wifi,
    meal: this.meal,
    properties: this.properties

 const formData = new FormData();
  Object.keys(data).map(e => {
    formData.append(e, data[e]);
  });
  for (let i = 0; i < this.images.length; i++) {
    formData.append("images[]", this.images[i]);
  }
  for (let i = 0; i < this.props.length; i++) {
    formData.append("props[]", this.props[i]);
  }
  for (let i = 0; i < this.university.length; i++) {
    formData.append("university[]", this.university[i]);
  }
  formData.append("_method", "PUT");
  if (this.logo) {
    formData.append("logo", this.logo);
  }
  if (this.cover) {
    formData.append("cover", this.cover);
  }
  console.log(formData);
  this.$Progress.start();
  //this.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  this.axios.post("dorms/" + this.id, formData).then(response => {
    console.log(response.data);
    if (response.status == 200) {
      this.$Progress.finish();
    }
  });
},
</code>```

in headers section inside formData, I see properties as objects

```<code>  member: null
  capacity: 28
  is_wifi: 0
  meal: 0
  properties: [object Object],[object Object],[object Object]
  content: <p>null</p>
  content_en: <p>Under Construction</p>
</code>```

答:
Overlooking the syntax errors in the provided code

The FormData.append() method will only accept a String or Blob. So when you pass in an object of any type (Array, Object, Function...) the .toString() method of that object is forced to run immediately. So, an Object's .toString() method outputs [Object object] and that gets stored in your FormData object.

To fix that:

Change:

```<code>formData.append(e, data[e])
</code>```

To:

```<code>formData.append(e, JSON.stringify(data[e]))
</code>```

you may want to test if data[e] doesn't contain a string first.

With that said

You go to a great deal of trouble to use FormData when it is just not necessary. Axios is designed to parse your Objects (deeply) automatically if you let it. It does that with FormData objects too, but you overcomplicated all of this.

You should consider NOT using FormData at all and simply send your data object directly in the Axios POST request.

To do that you will have to change the encoding to JSON because Axios default is url-form-encoded

Body:
I am working on a project with vuejs and to handle my AJAX requests I use Axios, the problem is I can not send array inside my formData, I see [object] on my request in network tab of developers panel.  Is it possible to pass as a parameter to a POST request with an array of objects inside main object, of this type: inside my object I have an array with lenght 2 as below

  (3) [{…}, {…}, {…}, __ob__: Observer]
  0:
  created_at: "2018-12-16 18:37:00"
  id: 1
  properties: Array(8)
  0: {…}
  1: {…}
  2: {…}
  3: {…}
  4: {…}
  5: {…}
  6: {…}
  7: {…}
  title: "Building properties"
  updated_at: "2018-12-16 18:37:00"
 __proto__: Object
 1: {…}
 2: {…}

I tried JSON.stringy both for array and whole object but I get 405 method not allowed. I also tried adding config. I see some solution as paramsSerializer but can not understand where I should write it exactly.

   var data = {
    user_id: this.user_info,
    type_id: this.dorm_type,
    city_id: this.city,
    district_id: this.district,
    is_active: this.is_active,
    name: this.name,
    slug: this.slug,
    keywords: this.keywords,
    description: this.description,
    member: this.member,
    capacity: this.capacity,
    is_wifi: this.is_wifi,
    meal: this.meal,
    properties: this.properties

 const formData = new FormData();
  Object.keys(data).map(e => {
    formData.append(e, data[e]);
  });
  for (let i = 0; i < this.images.length; i++) {
    formData.append("images[]", this.images[i]);
  }
  for (let i = 0; i < this.props.length; i++) {
    formData.append("props[]", this.props[i]);
  }
  for (let i = 0; i < this.university.length; i++) {
    formData.append("university[]", this.university[i]);
  }
  formData.append("_method", "PUT");
  if (this.logo) {
    formData.append("logo", this.logo);
  }
  if (this.cover) {
    formData.append("cover", this.cover);
  }
  console.log(formData);
  this.$Progress.start();
  //this.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
  this.axios.post("dorms/" + this.id, formData).then(response => {
    console.log(response.data);
    if (response.status == 200) {
      this.$Progress.finish();
    }
  });
},

in headers section inside formData, I see properties as objects

  member: null
  capacity: 28
  is_wifi: 0
  meal: 0
  properties: [object Object],[object Object],[object Object]
  content:
null

  content_en:
Under Construction

Body:
Overlooking the syntax errors in the provided code

The FormData.append() method will only accept a String or Blob. So when you pass in an object of any type (Array, Object, Function...) the .toString() method of that object is forced to run immediately. So, an Object's .toString() method outputs [Object object] and that gets stored in your FormData object.

To fix that:

Change:

formData.append(e, data[e])

To:

formData.append(e, JSON.stringify(data[e]))

you may want to test if data[e] doesn't contain a string first.

With that said

You go to a great deal of trouble to use FormData when it is just not necessary. Axios is designed to parse your Objects (deeply) automatically if you let it. It does that with FormData objects too, but you overcomplicated all of this.

You should consider NOT using FormData at all and simply send your data object directly in the Axios POST request.

To do that you will have to change the encoding to JSON because Axios default is url-form-encoded