问:
Add Nsattributed string and string in swift
I having the Dynamic data, I load that data into tableview but these data having the mixing of Attributed and normal strings.

Here I getting the as "Tap here" ,I want to dilate that string with Blue colour and pick on that it need to open the url.

I write following code but it gives error.

Binary operator '+' cannot be applied to operands of type 'String' and
  'NSMutableAttributedString'

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WhatisrewardsTableViewCell", for: indexPath)as! WhatisrewardsTableViewCell
        cell.imageview.image = images[indexPath.section][indexPath.row]
        cell.titlelbl.text = tilenames[indexPath.section][indexPath.row]
        cell.desclbl.text = descriptions[indexPath.section][indexPath.row]

        let value = " here.".withTextColor(UIColor.disSatifyclr)

        if (cell.desclbl.text?.contains("tap"))!{
           // cell.desclbl.text?.attributedString
            cell.desclbl.text = descriptions[indexPath.section][indexPath.row] + value
        }

        cell.desclbl.addLineSpacing()
        return cell
    }
</code>```

答:
You can not append the NSAttributedString to String objects. I would suggest that you generate a normal String and then add the attributed parameters to it.

```<code>func prepareURLString() -> NSMutableAttributedString {

        let masterString = "To navigate to google Tap Here."

        let formattedString = NSMutableAttributedString(string: masterString)

        let formattedStringAttribute = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),
            NSAttributedString.Key.foregroundColor: UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1),
            ] as [NSAttributedString.Key : Any]

        let privacyPolicyAttribute = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .bold),
            NSAttributedString.Key.foregroundColor: UIColor.blue,
            NSAttributedString.Key.underlineStyle: 1,
            NSAttributedString.Key.link: URL(string: "https://www.google.com")!
            ] as [NSAttributedString.Key : Any]

        formattedString.addAttributes(formattedStringAttribute, range: NSMakeRange(0, formattedString.length))

        let privacyPolicyRange = (masterString as NSString).range(of: "Tap Here")
        formattedString.addAttributes(privacyPolicyAttribute, range: privacyPolicyRange)

        return formattedString
    }
</code>```

This function will return a attributed string which you can use however you want. With tableview you can pass some parameters and modify the cell's attributes strings. I have added a google link behind the 'Tap Here' and its showing the output like below :

I hope I got your question right and this helps you in some way.

Body:
I having the Dynamic data, I load that data into tableview but these data having the mixing of Attributed and normal strings.

Here I getting the as "Tap here" ,I want to dilate that string with Blue colour and pick on that it need to open the url.

I write following code but it gives error.

Binary operator '+' cannot be applied to operands of type 'String' and
  'NSMutableAttributedString'

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "WhatisrewardsTableViewCell", for: indexPath)as! WhatisrewardsTableViewCell
        cell.imageview.image = images[indexPath.section][indexPath.row]
        cell.titlelbl.text = tilenames[indexPath.section][indexPath.row]
        cell.desclbl.text = descriptions[indexPath.section][indexPath.row]

        let value = " here.".withTextColor(UIColor.disSatifyclr)

        if (cell.desclbl.text?.contains("tap"))!{
           // cell.desclbl.text?.attributedString
            cell.desclbl.text = descriptions[indexPath.section][indexPath.row] + value
        }

        cell.desclbl.addLineSpacing()
        return cell
    }

Body:
You can not append the NSAttributedString to String objects. I would suggest that you generate a normal String and then add the attributed parameters to it.

func prepareURLString() -> NSMutableAttributedString {

        let masterString = "To navigate to google Tap Here."

        let formattedString = NSMutableAttributedString(string: masterString)

        let formattedStringAttribute = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .regular),
            NSAttributedString.Key.foregroundColor: UIColor(red: 51.0/255.0, green: 51.0/255.0, blue: 51.0/255.0, alpha: 1),
            ] as [NSAttributedString.Key : Any]

        let privacyPolicyAttribute = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 13, weight: .bold),
            NSAttributedString.Key.foregroundColor: UIColor.blue,
            NSAttributedString.Key.underlineStyle: 1,
            NSAttributedString.Key.link: URL(string: "https://www.google.com")!
            ] as [NSAttributedString.Key : Any]

        formattedString.addAttributes(formattedStringAttribute, range: NSMakeRange(0, formattedString.length))

        let privacyPolicyRange = (masterString as NSString).range(of: "Tap Here")
        formattedString.addAttributes(privacyPolicyAttribute, range: privacyPolicyRange)

        return formattedString
    }

This function will return a attributed string which you can use however you want. With tableview you can pass some parameters and modify the cell's attributes strings. I have added a google link behind the 'Tap Here' and its showing the output like below :

I hope I got your question right and this helps you in some way.


来源: stackexchange

问:
Android: How to scroll a parentView when child containing recyclerView is scrolled
I have created an app that contains a viewPager inside the mainActivity, this viewPager contains 5 fragments, of which 4 are recyclerViews and one is a normal linearLayout containing some text...

Here is a screenshot of the app, not all tabs in the tablayout are visible:

Now, as you might have seen already, there isn't much space in the viewPager for the user to see anything, so they have to scroll too much to view things in the recylerView. I want to modify my app so that when the user tries to scroll inside the recyclerView, the visible part of the mainActivity is scrolled down till the recyclerView occupies the entire page and then the recyclerView begins to scroll normally.

Can someone please help me implement this type of scroll feature into my app. You can just check out this app for a reference to what I'm saying. Just open up any movie or tvSeries and then try scrolling, the mainActivity gets scrolled first and then the rest of the layout.... Can someone please help. I've already tried the solutions on stackOverflow and many of them don't work, I also tried to google for a solution, but didn't get anything useful....

Here is the code for my adapter:

```<code>public class cardViewAdapterCreditsCast extends RecyclerView.Adapter<cardViewAdapterCreditsCast.ViewHolder> {

private Context context;
private List<creditsModel> creditsModels;

public cardViewAdapterCreditsCast(Context context, List<creditsModel> creditsModels) {
    this.context = context;
    this.creditsModels = creditsModels;
}

@Override
public cardViewAdapterCreditsCast.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_cast_row, parent, false);

    return new cardViewAdapterCreditsCast.ViewHolder(view);
}

@Override
public void onBindViewHolder(cardViewAdapterCreditsCast.ViewHolder holder, int position) {
    final creditsModel creditsModel = creditsModels.get(position);

    int tempNumber = holder.celebImage.getWidth();
    holder.celebImage.setMinimumHeight(tempNumber);
    holder.celebImage.setMaxHeight(tempNumber + 1);

    String imagePath = "https://image.tmdb.org/t/p/w500" + creditsModel.getProfilePath();

    holder.starringAs.setText(creditsModel.getCharacter());
    holder.celebName.setText(creditsModel.getActorName());

    if (creditsModel.getProfilePath() != null) {
        Picasso.with(context).load(imagePath).transform(new CircleTransform()).into(holder.celebImage);
    } else
        holder.celebImage.setBackgroundResource(R.drawable.not_found);
}

@Override
public int getItemCount() {
    return creditsModels.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    public ImageView celebImage;
    public TextView celebName;
    public TextView starringAs;

    private LinearLayout linearLayout;

    public ViewHolder(View itemView) {
        super(itemView);

        linearLayout = (LinearLayout) itemView.findViewById(R.id.castRowMainLinearLayout);

        celebImage = (ImageView) itemView.findViewById(R.id.castRowImage);
        celebName = (TextView) itemView.findViewById(R.id.castRowName);
        starringAs = (TextView) itemView.findViewById(R.id.castRowAppearance);
        }
    }
}
</code>```

答: Use nested Scrollview if there are more than one scrollview or recyclerview.</p>

ContentLicense: CC BY-SA 3.0

Body:
I have created an app that contains a viewPager inside the mainActivity, this viewPager contains 5 fragments, of which 4 are recyclerViews and one is a normal linearLayout containing some text...

Here is a screenshot of the app, not all tabs in the tablayout are visible:

Now, as you might have seen already, there isn't much space in the viewPager for the user to see anything, so they have to scroll too much to view things in the recylerView. I want to modify my app so that when the user tries to scroll inside the recyclerView, the visible part of the mainActivity is scrolled down till the recyclerView occupies the entire page and then the recyclerView begins to scroll normally.

Can someone please help me implement this type of scroll feature into my app. You can just check out this app for a reference to what I'm saying. Just open up any movie or tvSeries and then try scrolling, the mainActivity gets scrolled first and then the rest of the layout.... Can someone please help. I've already tried the solutions on stackOverflow and many of them don't work, I also tried to google for a solution, but didn't get anything useful....

Here is the code for my adapter:

public class cardViewAdapterCreditsCast extends RecyclerView.Adapter<cardViewAdapterCreditsCast.ViewHolder> {

private Context context;
private List<creditsModel> creditsModels;

public cardViewAdapterCreditsCast(Context context, List<creditsModel> creditsModels) {
    this.context = context;
    this.creditsModels = creditsModels;
}

@Override
public cardViewAdapterCreditsCast.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.new_cast_row, parent, false);

    return new cardViewAdapterCreditsCast.ViewHolder(view);
}

@Override
public void onBindViewHolder(cardViewAdapterCreditsCast.ViewHolder holder, int position) {
    final creditsModel creditsModel = creditsModels.get(position);

    int tempNumber = holder.celebImage.getWidth();
    holder.celebImage.setMinimumHeight(tempNumber);
    holder.celebImage.setMaxHeight(tempNumber + 1);

    String imagePath = "https://image.tmdb.org/t/p/w500" + creditsModel.getProfilePath();

    holder.starringAs.setText(creditsModel.getCharacter());
    holder.celebName.setText(creditsModel.getActorName());

    if (creditsModel.getProfilePath() != null) {
        Picasso.with(context).load(imagePath).transform(new CircleTransform()).into(holder.celebImage);
    } else
        holder.celebImage.setBackgroundResource(R.drawable.not_found);
}

@Override
public int getItemCount() {
    return creditsModels.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {

    public ImageView celebImage;
    public TextView celebName;
    public TextView starringAs;

    private LinearLayout linearLayout;

    public ViewHolder(View itemView) {
        super(itemView);

        linearLayout = (LinearLayout) itemView.findViewById(R.id.castRowMainLinearLayout);

        celebImage = (ImageView) itemView.findViewById(R.id.castRowImage);
        celebName = (TextView) itemView.findViewById(R.id.castRowName);
        starringAs = (TextView) itemView.findViewById(R.id.castRowAppearance);
        }
    }
}

ContentLicense: CC BY-SA 4.0


问:
Elastic Search Nest create connection
I have elastic search hosted on IIS with url as "https://somedomain.com/VD1".
I am able to access above url in Postman. I am trying to connect using below query

     EsNode = new Uri("https://somedomain.com/VD1/");
     EsConfig = new ConnectionSettings(EsNode);
     EsClient = new ElasticClient(EsConfig);

On trying to create index , I am observing that query are getting formed as
https://somedomain.com/index in place of https://somedomain.com/VD1/index leading to failure.

Is there a way that I can use https://somedomain.com/VD1 for connection

答:
Above issue was in Nest 7.0.0-alpha1 and was resolved in Nest 7.0.0-alpha2
https://github.com/elastic/elasticsearch-net/issues/3749</p>

Title: Elastic Search Nest create connection


问:
Is there any default strategy to prepare application for a resolution change?
How to prepare a Silverlight or WPF application to change from a big resolution to a small resolution?

I guess using dockpanel strategy only works for changing from a small to a big resolution.

So, is there any default strategy? Thanks.

Problem: I have a button the ends in the pixel 1024, 768. And I change the resolution to 800x600.

答:
Well, you could design your layout to Stretch and designing it with 800x600 in mind, so whenever the layout becomes larger than 800x600 it will fit. But...

if you really want something fancy, detect the change in the window size/ActualHeight and ActualWidth (using SizeChanged) then scale the the application according to size via code (using dynamic transforms).

For example, in the "LayoutRoot" in your main view:

```<code>var x = new ScaleTransform();
            x.ScaleX = .5; // Do fancy computation here
            x.ScaleY = .5; // Do fancy computation here
            this.LayoutRoot.RenderTransform = x;
</code>```

Just an idea, i mean if the screen is bigger than your design you enlarge and vice versa.

Hope this helps.

Body:
Well, you could design your layout to Stretch and designing it with 800x600 in mind, so whenever the layout becomes larger than 800x600 it will fit. But...

if you really want something fancy, detect the change in the window size/ActualHeight and ActualWidth (using SizeChanged) then scale the the application according to size via code (using dynamic transforms).

For example, in the "LayoutRoot" in your main view:

var x = new ScaleTransform();
            x.ScaleX = .5; // Do fancy computation here
            x.ScaleY = .5; // Do fancy computation here
            this.LayoutRoot.RenderTransform = x;

Just an idea, i mean if the screen is bigger than your design you enlarge and vice versa.

Hope this helps.


问:
screenShot image with Avplayer ios 10* is Black image
```<code>extension UIView {
    func capture() -> UIImage? {
        var image: UIImage?

        if #available(iOS 10.0, *) {
            let format = UIGraphicsImageRendererFormat()
            format.opaque = isOpaque
            let renderer = UIGraphicsImageRenderer(size: frame.size, format: format)
            image = renderer.image { context in
                drawHierarchy(in: frame, afterScreenUpdates: true)
            }
        } else {
            UIGraphicsBeginImageContextWithOptions(frame.size, isOpaque, UIScreen.main.scale)
            drawHierarchy(in: frame, afterScreenUpdates: true)
            image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
        }

        return image
    }
}
</code>```

答:
```<code>public extension AVAsset {
    func takeScreenshot(at: Double,completion: @escaping (UIImage?) -> Void) {
            DispatchQueue.global().async {
                let imageGenerator = AVAssetImageGenerator(asset: self)
                let time = CMTime(seconds: at, preferredTimescale: 600)
                let times = [NSValue(time: time)]
                imageGenerator.generateCGImagesAsynchronously(forTimes: times, completionHandler: { _, image, _, _, _ in
                    if let image = image {
                        completion(UIImage(cgImage: image))
                    } else {
                        completion(nil)
                    }
                })
            }
        }
}
</code>```


问:
How to parse the attestationObject in Node.js
I have mocked up the response from the front end in Node.js as seen below.

the attestationObject parameter is what is returned once the Yubikey has signed the challenge and its been converted to base64 for transport to the node server.

What i'm getting is an ArrayBuffer { byteLength: 226 } but I have no idea what to do with it.

I know i need to check the domain name the signed it and I need to store something with the users credentials so they can login again.

I understand there is loads of options, I just want to get a bare minimum passwordless register and login working.

```<code>const cbor = require("cbor");
const attestationObject = "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjE4mQ5WmgO3yl24XjxRqkP9LjqRYP-GsIubALB-5K_CK5FXMrOUa3OAAI1vMYKZIsLJfHwVQMAQABcapsmHtrsLJtfZ7RDcRm0iDgMlc5-CuP2XcNOwDy0uU2mU44ENk-EqtthH7huq8AipYfY0EvmfPRqQI-zI5GlAQIDJiABIVggZplpmQSKsJvg78INyrQUgBo9dv0vaZL6Qp15rOd6wMQiWCAx-ZeQ6T_xTMlY9cG3EWY54wT9Hd6EX7P7Ak-9uwauCA"
const clientDataJSON = "eyJjaGFsbGVuZ2UiOiJlVGR1TjJGaGFIaHhhRFJzT0RsdU1qTnRhMjgiLCJvcmlnaW4iOiJodHRwczovL2UzMDI3MTU3Lm5ncm9rLmlvIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9"
const id = "AFxqmyYe2uwsm19ntENxGbSIOAyVzn4K4_Zdw07APLS5TaZTjgQ2T4Sq22EfuG6rwCKlh9jQS-Z89GpAj7MjkQ"
const rawid = "AFxqmyYe2uwsm19ntENxGbSIOAyVzn4K4_Zdw07APLS5TaZTjgQ2T4Sq22EfuG6rwCKlh9jQS-Z89GpAj7MjkQ"

convertToBuffer(attestationObject)
.then((buffer) => {
 return parseAttestationObject(buffer)
})
.then((json) => {
    console.log(json)
})
.catch((err) => {
    console.log(err)
})

function convertToBuffer(base64) {
    return new Promise((resolve, reject) => {
        if (typeof base64 === "string") {
            base64 = base64.replace(/-/g, "+").replace(/_/g, "/");
            base64 = Buffer.from(base64, "base64");
            base64 = new Uint8Array(base64);
            resolve(base64.buffer);
        }

    })
}

function parseAttestationObject(attestationObject){
    return new Promise((resolve, reject) => {
        const authData = cbor.decodeAllSync(Buffer.from(attestationObject));
        const authnrDataArrayBuffer = authData[0].authData.buffer;
        console.log(authnrDataArrayBuffer)
        // What do I do with this authnrDataArrayBuffer? What needs saving to the database?
    })
}
</code>```

答:
It would be helpful if you would be a bit more exact about the exact issue, but in a nutshell:

You'd want to store the rawI This is the identifier that you need to pass in the allowCredentials object in the authentication step, so you'll need it.

The attestationobject is a CBOR encoded value. After some manipulations you should be able to extract a public key from this. You'll be able to to use this certificate to verify the response from the authenticator in the authentication step.

I'm leaving out any specific implementation steps, but please have a look at https://github.com/fido-alliance/webauthn-demo as this project implements webauthn for node.js as well, so you should be able to extract all relevant code from it.

Body:
I have mocked up the response from the front end in Node.js as seen below.

the attestationObject parameter is what is returned once the Yubikey has signed the challenge and its been converted to base64 for transport to the node server.

What i'm getting is an ArrayBuffer { byteLength: 226 } but I have no idea what to do with it.

I know i need to check the domain name the signed it and I need to store something with the users credentials so they can login again.

I understand there is loads of options, I just want to get a bare minimum passwordless register and login working.

const cbor = require("cbor");
const attestationObject = "o2NmbXRkbm9uZWdhdHRTdG10oGhhdXRoRGF0YVjE4mQ5WmgO3yl24XjxRqkP9LjqRYP-GsIubALB-5K_CK5FXMrOUa3OAAI1vMYKZIsLJfHwVQMAQABcapsmHtrsLJtfZ7RDcRm0iDgMlc5-CuP2XcNOwDy0uU2mU44ENk-EqtthH7huq8AipYfY0EvmfPRqQI-zI5GlAQIDJiABIVggZplpmQSKsJvg78INyrQUgBo9dv0vaZL6Qp15rOd6wMQiWCAx-ZeQ6T_xTMlY9cG3EWY54wT9Hd6EX7P7Ak-9uwauCA"
const clientDataJSON = "eyJjaGFsbGVuZ2UiOiJlVGR1TjJGaGFIaHhhRFJzT0RsdU1qTnRhMjgiLCJvcmlnaW4iOiJodHRwczovL2UzMDI3MTU3Lm5ncm9rLmlvIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9"
const id = "AFxqmyYe2uwsm19ntENxGbSIOAyVzn4K4_Zdw07APLS5TaZTjgQ2T4Sq22EfuG6rwCKlh9jQS-Z89GpAj7MjkQ"
const rawid = "AFxqmyYe2uwsm19ntENxGbSIOAyVzn4K4_Zdw07APLS5TaZTjgQ2T4Sq22EfuG6rwCKlh9jQS-Z89GpAj7MjkQ"

convertToBuffer(attestationObject)
.then((buffer) => {
 return parseAttestationObject(buffer)
})
.then((json) => {
    console.log(json)
})
.catch((err) => {
    console.log(err)
})

function convertToBuffer(base64) {
    return new Promise((resolve, reject) => {
        if (typeof base64 === "string") {
            base64 = base64.replace(/-/g, "+").replace(/_/g, "/");
            base64 = Buffer.from(base64, "base64");
            base64 = new Uint8Array(base64);
            resolve(base64.buffer);
        }

    })
}

function parseAttestationObject(attestationObject){
    return new Promise((resolve, reject) => {
        const authData = cbor.decodeAllSync(Buffer.from(attestationObject));
        const authnrDataArrayBuffer = authData[0].authData.buffer;
        console.log(authnrDataArrayBuffer)
        // What do I do with this authnrDataArrayBuffer? What needs saving to the database?
    })
}


问:
React Navigation is not a function?
I'm using React Navigation. I'm directing you to the conversation after the record insert page. I provide automatic renewal when I redirect. I'm sending a parameter. But that doesn't work. I don't know where I'm making a mistake.

I get this error.

Uncaught typeerror. TypeError: s.handleRefresh is not a function. (In 's.handleRefresh()', 's.handleRefresh' is undefined

LeadDetail.js Page

```<code>    static navigationOptions = ({ navigation }) => {
        const { params = {} } = navigation.state;
        return {
            title: 'Müşteri Adayı Detay',
            headerRight: (
                <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={() => navigation.navigate('CreateMeeting', { parentId: params.id, parentType: 'Lead' })} style={{marginRight: 12 }}>
                    <Icon
                        name="calendar-check-o"
                        size={25}
                        color="white"
                    />
                </TouchableHighlight>
            )
        };
    };
</code>```

CreateMeeting.js Page

```<code>    dataSuccess(response) {
        this.setState({ buttonLoading: false });

        Alert.alert(
            'Tebrikler!',
            'Meeting başarılı bir şekilde kayıt edildi',
            [
                { text: 'Tamam', onPress: () => this.props.navigation.navigate('Meeting', { refreshMeeting: true }) }
            ]
        );
    }
</code>```

Meeting.js Page

```<code>    static navigationOptions = ({ navigation }) => {
        const { params } = navigation.state;
        let refresh = navigation.getParam('refreshMeeting', false);

        if(refresh) {
            params.handleRefresh();
        }
        return {
            title: 'Görüşmeler',
            headerRight: (
                <View style={{ flexDirection: 'row' }}>
                    <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={navigation.getParam('setOverlay')}>
                        <Icon
                            name="filter"
                            size={25}
                            color="white"
                        />
                    </TouchableHighlight>

                    <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={navigation.getParam('setModalVisible')} style={{ marginRight: 12, marginLeft: 20 }}>
                        <Icon
                            name="plus"
                            size={25}
                            color="white"
                        />
                    </TouchableHighlight>
                </View>
            )
        };
    };
</code>```

答:
Are you setting the param handleRefresh? Instead of params.handleRefresh(); shouldn't it be params.refresh();?
Also, s.handleRefresh where is this in your code? I think there is a typo or something like that and I'm considering that s.handleRefresh is actually params.handleRefresh

Please edit your question if none of this is correct.

I don't know where you are setting the param handleRefresh, but if you are setting it (please check that and add the code where you do that), maybe here is the reason why this happens.

If you look at the docs they have a not

React Navigation doesn't guarantee that your screen component will be mounted before the header. Because the increaseCount param is set in componentDidMount, we may not have it available to us in navigationOptions. This usually will not be a problem because onPress for Button and Touchable components will do nothing if the callback is null. If you have your own custom component here, you should make sure it behaves as expected with null for its press handler prop.

This means that the header can render before the component calls setParams and that doens't load you params in the first time. What you need to do some checking to avoid that time when the header renders first.

```<code>//            added some checking
if(refresh && params && params.handleRefresh) {
    params.handleRefresh();
}
</code>```

Title: React Navigation is not a function?

Body:
I'm using React Navigation. I'm directing you to the conversation after the record insert page. I provide automatic renewal when I redirect. I'm sending a parameter. But that doesn't work. I don't know where I'm making a mistake.

I get this error.

Uncaught typeerror. TypeError: s.handleRefresh is not a function. (In 's.handleRefresh()', 's.handleRefresh' is undefined

LeadDetail.js Page

    static navigationOptions = ({ navigation }) => {
        const { params = {} } = navigation.state;
        return {
            title: 'Müşteri Adayı Detay',
            headerRight: (
                <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={() => navigation.navigate('CreateMeeting', { parentId: params.id, parentType: 'Lead' })} style={{marginRight: 12 }}>
                    <Icon
                        name="calendar-check-o"
                        size={25}
                        color="white"
                    />
                </TouchableHighlight>
            )
        };
    };

CreateMeeting.js Page

    dataSuccess(response) {
        this.setState({ buttonLoading: false });

        Alert.alert(
            'Tebrikler!',
            'Meeting başarılı bir şekilde kayıt edildi',
            [
                { text: 'Tamam', onPress: () => this.props.navigation.navigate('Meeting', { refreshMeeting: true }) }
            ]
        );
    }

Meeting.js Page

    static navigationOptions = ({ navigation }) => {
        const { params } = navigation.state;
        let refresh = navigation.getParam('refreshMeeting', false);

        if(refresh) {
            params.handleRefresh();
        }
        return {
            title: 'Görüşmeler',
            headerRight: (
                <View style={{ flexDirection: 'row' }}>
                    <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={navigation.getParam('setOverlay')}>
                        <Icon
                            name="filter"
                            size={25}
                            color="white"
                        />
                    </TouchableHighlight>

                    <TouchableHighlight activeOpacity={0.4} underlayColor='transparent' onPress={navigation.getParam('setModalVisible')} style={{ marginRight: 12, marginLeft: 20 }}>
                        <Icon
                            name="plus"
                            size={25}
                            color="white"
                        />
                    </TouchableHighlight>
                </View>
            )
        };
    };

Body:
Are you setting the param handleRefresh? Instead of params.handleRefresh(); shouldn't it be params.refresh();?
Also, s.handleRefresh where is this in your code? I think there is a typo or something like that and I'm considering that s.handleRefresh is actually params.handleRefresh

Please edit your question if none of this is correct.

I don't know where you are setting the param handleRefresh, but if you are setting it (please check that and add the code where you do that), maybe here is the reason why this happens.

If you look at the docs they have a not

React Navigation doesn't guarantee that your screen component will be mounted before the header. Because the increaseCount param is set in componentDidMount, we may not have it available to us in navigationOptions. This usually will not be a problem because onPress for Button and Touchable components will do nothing if the callback is null. If you have your own custom component here, you should make sure it behaves as expected with null for its press handler prop.

This means that the header can render before the component calls setParams and that doens't load you params in the first time. What you need to do some checking to avoid that time when the header renders first.

//            added some checking
if(refresh && params && params.handleRefresh) {
    params.handleRefresh();
}


问:
How to update a ColumnDataSource data for a MultiLine glyph?
I am trying to create a Bokeh application that plots multiple time-series, and allows the user to select a subset of the time-series using a CheckboxButtonGroup widget.  I would like to change the displayed graphs from python, rather than attempting to hide/un-hide lines on the javascript side.  I have attempted to do this by adding a multi-line and changing the values in its data source from a callback function.  This works fine when I change the contents of the time series, or when I remove a time series, but as soon as I attempt to add a time-series to the multi-line, I get an error on the javascript side (the chrome console prints Bokeh: Error handling message).

To be specific, I have a pandas data frame with a data column indexed by bucket names and timestamps:

```<code>data = pandas.DataFrame(...)
buckets = data.index.levels[0]
timestamps = data.index.levels[1]
</code>```

I have a multi-line graph and a control:

```<code>plot = bokeh.plotting.Figure(x_axis_type = "datetime")
multiline = plot.multi_line(xs = [], ys = [])
bucketsControl = bokeh.models.widgets.CheckboxButtonGroup(labels = list(buckets))
</code>```

And I have a callback function that updates the data source and is triggered by the control:

```<code>def update(value):
    xs = []
    ys = []
    for bucketIndex in bucketsControl.active:
        bucketName = bucketsControl.labels[bucketIndex]
        bucketData = data.loc[bucketName]
        series = bucketData["data"]
    xs.append(series.index.values)
    ys.append(series.values)
    multiline.data_source.data["xs"] = xs
    multiline.data_source.data["ys"] = ys

bucketsControl.on_click(update)
</code>```

I don't know for sure what's causing the problem here, but I've taken a look at the web socket traffic going between the Bokeh server and the web-browser when I attempt to add another time-series, and I see that it results in two ModelChanged updates: the first one adds another list to xs, and the seconds one adds a list to ys.  I suspect that the BokehJS client isn't able to handle that first update, where it has one more x series than y series.

Is there a way to make this multi-line update work? Or, is there another way to update the structure of the plot from python (e.g. adding a whole new line to the plot, rather than changing the data-source of an existing glyph)?

答:
You can use patch to update only the new data, minimizing the data that is going to be sent to the front-end

To update a entire line:

```<code>source = ColumnDataSource(dict(
    xs=[[1, 2, 3, 4, 5, 6]],
    ys=[[1, 2, 3, 4.2, 2.2, 0.5]],
))
source.patch({
    'ys' : [(0, [1, 2, 3, 4, 5, 6])]
})
</code>```

To update line fragments:

```<code>source = ColumnDataSource(dict(
    xs=[np.array([1, 2, 3, 4, 5, 6])],
    ys=[np.array([1, 2, 3, 4.2, 2.2, 0.5])],
))
source.patch({
    'ys' : [([0, slice(3, 6)], np.array([4, 5, 6]))]
})
</code>```

There is a hacky way to remove the whole, because this is not supported by bokeh

```<code>source.patch({
    'ys' : [(0,[''])],     # or 'ys' : [(0,numpy.array([numpy.nan]))],
})
</code>```

Also, you can update many columns at the same time just adding keys to the patch dictionary

Body:
I am trying to create a Bokeh application that plots multiple time-series, and allows the user to select a subset of the time-series using a CheckboxButtonGroup widget.  I would like to change the displayed graphs from python, rather than attempting to hide/un-hide lines on the javascript side.  I have attempted to do this by adding a multi-line and changing the values in its data source from a callback function.  This works fine when I change the contents of the time series, or when I remove a time series, but as soon as I attempt to add a time-series to the multi-line, I get an error on the javascript side (the chrome console prints Bokeh: Error handling message).

To be specific, I have a pandas data frame with a data column indexed by bucket names and timestamps:

data = pandas.DataFrame(...)
buckets = data.index.levels[0]
timestamps = data.index.levels[1]

I have a multi-line graph and a control:

plot = bokeh.plotting.Figure(x_axis_type = "datetime")
multiline = plot.multi_line(xs = [], ys = [])
bucketsControl = bokeh.models.widgets.CheckboxButtonGroup(labels = list(buckets))

And I have a callback function that updates the data source and is triggered by the control:

def update(value):
    xs = []
    ys = []
    for bucketIndex in bucketsControl.active:
        bucketName = bucketsControl.labels[bucketIndex]
        bucketData = data.loc[bucketName]
        series = bucketData["data"]
    xs.append(series.index.values)
    ys.append(series.values)
    multiline.data_source.data["xs"] = xs
    multiline.data_source.data["ys"] = ys

bucketsControl.on_click(update)

I don't know for sure what's causing the problem here, but I've taken a look at the web socket traffic going between the Bokeh server and the web-browser when I attempt to add another time-series, and I see that it results in two ModelChanged updates: the first one adds another list to xs, and the seconds one adds a list to ys.  I suspect that the BokehJS client isn't able to handle that first update, where it has one more x series than y series.

Is there a way to make this multi-line update work? Or, is there another way to update the structure of the plot from python (e.g. adding a whole new line to the plot, rather than changing the data-source of an existing glyph)?

Body:
You can use patch to update only the new data, minimizing the data that is going to be sent to the front-end

To update a entire line:

source = ColumnDataSource(dict(
    xs=[[1, 2, 3, 4, 5, 6]],
    ys=[[1, 2, 3, 4.2, 2.2, 0.5]],
))
source.patch({
    'ys' : [(0, [1, 2, 3, 4, 5, 6])]
})

To update line fragments:

source = ColumnDataSource(dict(
    xs=[np.array([1, 2, 3, 4, 5, 6])],
    ys=[np.array([1, 2, 3, 4.2, 2.2, 0.5])],
))
source.patch({
    'ys' : [([0, slice(3, 6)], np.array([4, 5, 6]))]
})

There is a hacky way to remove the whole, because this is not supported by bokeh

source.patch({
    'ys' : [(0,[''])],     # or 'ys' : [(0,numpy.array([numpy.nan]))],
})

Also, you can update many columns at the same time just adding keys to the patch dictionary


问:
How to create a RandomAccessStreamReference to access a resource defined in a .rc file?
Working in "traditional" C++, I would like to embed a ONNX file (for usage with WinML) into a DLL as a resource, adding it to the .rc file: IDR_NETWORK     ONNX    "network.onnx"
 That is working fine, I can access the resource using the FindResource, LoadResource, and LockResource functions.

For loading this file with WinML, there is a method LearningModel::LoadFromStream taking a winrt::Windows::Storage::Streams::RandomAccessStreamReferenceas argument. That seems to be the right interface to load the network from something else than a file.

I tried with winrt::Windows::Storage::Streams::RandomAccessStreamReference::CreateFromUri but I do not see how to create an URI for the embedded resource.

My current workaround is to extract the resource, save to a temporary file and load using LearningModel::LoadFromFilePath from the temporary file.

Best would be some example code how to directly access the resource.

Alternativly creating a RandomAccessStreamReference to access the pointer returned by LockResource would help.

答:
The following example (pseudo) code does the trick:

```<code>        HRSRC hResource = ::FindResource(hModule, MAKEINTRESOURCE(iRessourceID), L"ONNX"))
        HGLOBAL hMem = ::LoadResource(hModule, hResource)

        const BYTE* pData = (const BYTE*)::LockResource(hMem);
        const size_t iSize = ::SizeofResource(hModule, hResource);

        using namespace Windows::Storage;
        using namespace winrt::Windows::Storage::Streams;

        InMemoryRandomAccessStream modelStream;
        DataWriter writer(modelStream);
        writer.WriteBytes(array_view<const unsigned char>(pData, pData + iSize));
        writer.StoreAsync().get();

        ::FreeResource(hMem);

        modelStream.Seek(0);

        auto modelStreamReference = RandomAccessStreamReference::CreateFromStream(modelStream);
        auto model = LearningModel::LoadFromStream(modelStreamReference);
</code>```

This codes creates a copy of the data, potentially that could be improved.

Body:
The following example (pseudo) code does the trick:

        HRSRC hResource = ::FindResource(hModule, MAKEINTRESOURCE(iRessourceID), L"ONNX"))
        HGLOBAL hMem = ::LoadResource(hModule, hResource)

        const BYTE* pData = (const BYTE*)::LockResource(hMem);
        const size_t iSize = ::SizeofResource(hModule, hResource);

        using namespace Windows::Storage;
        using namespace winrt::Windows::Storage::Streams;

        InMemoryRandomAccessStream modelStream;
        DataWriter writer(modelStream);
        writer.WriteBytes(array_view<const unsigned char>(pData, pData + iSize));
        writer.StoreAsync().get();

        ::FreeResource(hMem);

        modelStream.Seek(0);

        auto modelStreamReference = RandomAccessStreamReference::CreateFromStream(modelStream);
        auto model = LearningModel::LoadFromStream(modelStreamReference);

This codes creates a copy of the data, potentially that could be improved.


问:
Angular 7: Await function in interceptor
I have built an error interceptor in my first Angular application which is all new for me. The interceptor tries to refresh a Firebase authorization token when a 401 response code occures. Therefore I have written the following code:

```<code>@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private alertService: AlertService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                const reference = this;
                this.authService.getToken(currentUser, true).then(t => {
                    // How do I await and return this properly?
                    return reference.updateTokenAndRetry(request, next, currentUser, t);
                }); // Get token and refresh
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}
</code>```

The token gets refreshed fine. However the network call is not being executed after the refresh, which reference.updateTokenAndRetry(request, next, currentUser, t); should do.

I assume the reason for this, is that this.authService.getToken(currentUser, true) returns a Promise (this is the Firebase plugin and can't be changed). I want to return return reference.updateTokenAndRetry(request, next, currentUser, t); but this is not possible since it's in an async function block.

How can I await or return the next network call? I can't make the intercept function async. I am pretty stuck at this point.

答:
Instead of trying to return an async promise you should convert your promise to an observable using the RxJS 'from' operator as described in this post: Convert promise to observable.

This will result in a correct return type of Observable> for your interceptor.

Your code would look like something like the following (assuming you only send one request at a time):

```<code>intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                // Return a newly created function here
                return this.refreshToken(currentUser, request, next);
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

refreshToken(currentUser: any, request: any, next: any) {
    // By making use of the from operator of RxJS convert the promise to an observable
    return from(this.authService.getToken(currentUser, true)).pipe(
        switchMap(t => this.updateTokenAndRetry(request, next, currentUser, t))
    )
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}
</code>```

Hope this helps!

Body:
I have built an error interceptor in my first Angular application which is all new for me. The interceptor tries to refresh a Firebase authorization token when a 401 response code occures. Therefore I have written the following code:

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authService: AuthService, private alertService: AlertService) { }

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                const reference = this;
                this.authService.getToken(currentUser, true).then(t => {
                    // How do I await and return this properly?
                    return reference.updateTokenAndRetry(request, next, currentUser, t);
                }); // Get token and refresh
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}

The token gets refreshed fine. However the network call is not being executed after the refresh, which reference.updateTokenAndRetry(request, next, currentUser, t); should do.

I assume the reason for this, is that this.authService.getToken(currentUser, true) returns a Promise (this is the Firebase plugin and can't be changed). I want to return return reference.updateTokenAndRetry(request, next, currentUser, t); but this is not possible since it's in an async function block.

How can I await or return the next network call? I can't make the intercept function async. I am pretty stuck at this point.

Body:
Instead of trying to return an async promise you should convert your promise to an observable using the RxJS 'from' operator as described in this post: Convert promise to observable.

This will result in a correct return type of Observable> for your interceptor.

Your code would look like something like the following (assuming you only send one request at a time):

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
        catchError(err => {
            if (err.status === 401) {
                let user = localStorage.getItem('currentUser');
                if (!user) {
                    this.logout(false);
                    return throwError(err.error);
                }
                let currentUser = JSON.parse(user);
                if (!currentUser || !currentUser.stsTokenManager || !currentUser.stsTokenManager.accessToken) {
                    this.logout(false);
                    return throwError(err.error);
                }
                // Return a newly created function here
                return this.refreshToken(currentUser, request, next);
            }
            this.alertService.showAlert({
                text: 'Fout tijdens het verzenden van het verzoek',
            });
            return throwError(err.error);
        })
    );
}

refreshToken(currentUser: any, request: any, next: any) {
    // By making use of the from operator of RxJS convert the promise to an observable
    return from(this.authService.getToken(currentUser, true)).pipe(
        switchMap(t => this.updateTokenAndRetry(request, next, currentUser, t))
    )
}

updateTokenAndRetry(request: HttpRequest<any>, next: HttpHandler, currentUser: any, token: string): Observable<HttpEvent<any>> {
    // Update local stored user
    currentUser.stsTokenManager.accessToken = token;
    localStorage.setItem('currentUser', JSON.stringify(currentUser));

    // Add the new token to the request
    request = request.clone({
        setHeaders: {
            Authorization: token,
        },
    });

    return next.handle(request);
}

Hope this helps!


问:
Capturing Apscedular job exceptions to Sentry
I'm using apscheduler to process few things in background.

I'd like to capture and report possible exceptions to Sentry. My code looks like this:

```<code>sentry = Client(dsn=SENTRY_DSN)

def sample_method():
     # some processing..

     raise ConnectionError

def listen_to_exceptions(event):
    if event.exception:
        # I was hoping raven will capture the exception using  sys.exc_info(), but it's not
        sentry.captureException()

scheduler = BlockingScheduler()

scheduler.add_listener(listen_to_exceptions, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

scheduler.add_job(sample_method, 'interval', minutes=5, max_instances=1)

# run forever!!!
scheduler.start()
</code>```

But instead capturing the exception, it generates more exceptions trying to report it to Sentry.

```<code>ConnectionError
Error notifying listener
Traceback (most recent call last):
  File "/.../venv/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 825, in _dispatch_event
    cb(event)
  File "app.py", line 114, in listen_to_exceptions
    sentry.captureException(event.exception)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 814, in captureException
    'raven.events.Exception', exc_info=exc_info, **kwargs)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 623, in capture
    if self.skip_error_for_logging(exc_info):
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 358, in skip_error_for_logging
    key = self._get_exception_key(exc_info)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 345, in _get_exception_key
    code_id = id(exc_info[2] and exc_info[2].tb_frame.f_code)
TypeError: 'ConnectionError' object is not subscriptable
</code>```

I'm trying to use event listener according to the docs. Is there another way to capture exceptions in executed jobs?

Of course I could add try except blocks to each job function. I'm just trying to understand if there's a way to do it with apscedular, because I've 20+ jobs and adding sentry.captureException() every where seems like  repetition.

答:
The documentation has been updated. So you have to do it the following way:</p>

```<code>from sentry_sdk import capture_exception
....
def sentry_listener(event):
    if event.exception:
        capture_exception(event.exception)

scheduler.add_listener(sentry_listener, EVENT_JOB_ERROR)
</code>```

Body:
I'm using apscheduler to process few things in background.

I'd like to capture and report possible exceptions to Sentry. My code looks like this:

sentry = Client(dsn=SENTRY_DSN)

def sample_method():
     # some processing..

     raise ConnectionError

def listen_to_exceptions(event):
    if event.exception:
        # I was hoping raven will capture the exception using  sys.exc_info(), but it's not
        sentry.captureException()

scheduler = BlockingScheduler()

scheduler.add_listener(listen_to_exceptions, EVENT_JOB_EXECUTED | EVENT_JOB_ERROR)

scheduler.add_job(sample_method, 'interval', minutes=5, max_instances=1)

# run forever!!!
scheduler.start()

But instead capturing the exception, it generates more exceptions trying to report it to Sentry.

ConnectionError
Error notifying listener
Traceback (most recent call last):
  File "/.../venv/lib/python3.6/site-packages/apscheduler/schedulers/base.py", line 825, in _dispatch_event
    cb(event)
  File "app.py", line 114, in listen_to_exceptions
    sentry.captureException(event.exception)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 814, in captureException
    'raven.events.Exception', exc_info=exc_info, **kwargs)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 623, in capture
    if self.skip_error_for_logging(exc_info):
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 358, in skip_error_for_logging
    key = self._get_exception_key(exc_info)
  File "/.../venv/lib/python3.6/site-packages/raven/base.py", line 345, in _get_exception_key
    code_id = id(exc_info[2] and exc_info[2].tb_frame.f_code)
TypeError: 'ConnectionError' object is not subscriptable

I'm trying to use event listener according to the docs. Is there another way to capture exceptions in executed jobs?

Of course I could add try except blocks to each job function. I'm just trying to understand if there's a way to do it with apscedular, because I've 20+ jobs and adding sentry.captureException() every where seems like  repetition.

Body:
The documentation has been updated. So you have to do it the following way:

from sentry_sdk import capture_exception
....
def sentry_listener(event):
    if event.exception:
        capture_exception(event.exception)

scheduler.add_listener(sentry_listener, EVENT_JOB_ERROR)


问:
How to fix 'Cannot read property of undefined' error in Angular post request
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

```<code>createdBy: string from email input,
paymentMethod: string from paymentMethod select input,
</code>```

But what I get is:

```<code>createdBy: null,
paymentMethod: null
</code>```

Interfaces

```<code>export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}
</code>```

service.ts

```<code>public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );
</code>```

component.ts

```<code>ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

</code>```

component.html

```<code><form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">
        <h5 *ngIf="success">Your form is valid!</h5>
          <div class="form-group col-md-6">
            <label for="inputEmail">Email</label>
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">
            <div *ngIf="submitted && shippingForm.controls.email.errors" class="error">
              <div *ngIf="shippingForm.controls.email.errors.required">Your email is required!</div>
            </div>
          </div>
        </div>
        <div class="form-group col-md-6">
            <label for="payment">Payment Method: </label>
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>
            <div *ngIf="submitted && shippingForm.controls.paymentMethod.errors" class="error">
              <div *ngIf="shippingForm.controls.paymentMethod.errors.required">Your preferred payment method is required!</div>
            </div>
          </div>
</form>
</code>```

答:
Try with below code in newOrder function.

createdBy: billingForm.value.email,

paymentMethod: billingForm.value.paymentMethod,

Body:
I'm getting these errors and I'm not sure how to fix it. I am making a form that will make a post request to an API.

ERROR TypeError: Cannot read property 'email' of undefined

ERROR TypeError: Cannot read property 'paymentMethod' of undefined

I am expecting:

createdBy: string from email input,
paymentMethod: string from paymentMethod select input,

But what I get is:

createdBy: null,
paymentMethod: null

Interfaces

export interface BillingForm {
    fullName: string;
    email: string;
    address: string;
    city: string;
    paymentMethod: string;

  }

export interface Order {
  id?: number;
  companyId: number;
  created: string;
  createdBy: string;
  paymentMethod: string;
  totalPrice: number;
  status: number;
  orderRows: OrderRows[];
}

service.ts

public postOrder(order: Order): Observable<Order> {
      console.log(order);
      return this.http.post<Order>(this.ordersURL, order, httpOptions).pipe(
        catchError(this.handleError('postOrder', order))
      );

component.ts

ngOnInit() {

    this.shippingForm = this.formBuilder.group({
      name: ['', Validators.required],
      email: ['', Validators.required],
      address: ['', Validators.required],
      paymentMethod: ['', Validators.required],
      city: ['', Validators.required],
    })
  }

  onSubmit(billingForm: BillingForm) {
    const order = this.newOrder(billingForm);

    this.productService.postOrder(order).subscribe (
      response => console.log('success', response),
      error => console.log('error', error)
    )

    this.submitted = true;

    if(this.shippingForm.invalid) {
      return;
    }
    this.success = true;

  }

  newOrder(billingForm: BillingForm ): Order {
    return {
      companyId: 6,
      created: moment().locale("sv").format("YYYY-MM-DDTLTS"),
      createdBy: billingForm.email,
      paymentMethod: billingForm.paymentMethod,
      totalPrice: this.totalPrice,
      status: 0,
      orderRows: this.orderRows

    }
  }

  get email() {
    return this.shippingForm.get("email") as FormControl;
  }

  get paymentMethod() {
    return this.shippingForm.get("paymentMethod") as FormControl;
  }

component.html

<form [formGroup]="shippingForm" (ngSubmit)="onSubmit(billingForm)">

Your form is valid!

            Email
            <input type="email" formControlName="email" class="form-control" id="inputEmail" placeholder="Email">

Your email is required!

            Payment Method:
            <select type="select" formControlName="paymentMethod" class="form-control" id="payment"
              aria-placeholder="Mastercard">
              <option selected> Choose...</option>
              <option *ngFor="let paymentMethod of paymentMethods">
                {{ paymentMethod }}
              </option>
            </select>

Your preferred payment method is required!

</form>


问:
Best way to design soundex based search
I have a table of forum posts, and want to improve the basic search functionality as we get a lot of users from all over the world who are not native English speakers and will have trouble finding results when they spell incorrectly.  The current forum search is exact.

Which of these designs will perform best?  Assume the database has 500,000 records and the search is used frequently.  Ideally I would like it to search every record.

Design One

Along side each forum post, I store soundex_post, which contains all the soundex data.  When a search is run, it soundexes all search terms, and does a LIKE operation on the soundex fields.

Design Two

I normalise it.  Every soundex code is stored in a new table, tblSoundexCodes.  Then there is a table tblForumPostSoundexCodes:

ID | Post_ID | SoundexCode_ID | Count

Then when a soundex is searched for, I simply pull out all the Post_IDs where SoundexCode_ID = n

Am I correct that method two will be considerably faster, but that it will be a lot harder to maintain (IE, when people edit posts).

答:
I have some doubts about your idea.

Let's take your own answer to one of the comments:

"@Frank is MSSQL, probably only going to be express edition, and I used soundex as an example I'll probably be implementing a more up to date algorithm"

This simple comments has 15 words (I discarded those shorter than 4 characters).
So you will have potentially 15 different records pointing here with value "1".

What if I, a non-native English speaker, decide to search for ("esample" and "dait")? Will you offer the ability to search for more than one word? With and-? or-? not-?

Wouldn't it be better to run the search as-is and provide a "maybe you are looking for 'Example and Date'?" like Google or Wikipedia do?

Title: Best way to design soundex based search


问:
gradle.user.home - set in gradle.properties, build.gradle, or settings.gradle to a project-relative location?
By default, gradle.user.home is set to ~/.gradle - I'd like to change it to a directory relative to the project, rather than the developer's home directory.

I know you can do so when you invoke gradle, like so:

```<code>$ gradle --gradle-user-home=./project-relative-directory
</code>```

Or

```<code>$ gradle -Dgradle.user.home=./project-relative-directory
</code>```

I know you can change the location of the build cache by adding the following to settings.gradle:

```<code>buildCache {
    local {
        // Set local build cache directory.
        directory = "${settingsDir}/build-cache"
    }
}
</code>```

But gradle continues to use gradle.user.home for other caching.

The manual claims that you can specify gradle.user.home in gradle.properties, like so:

```<code>systemProp.gradle.user.home=./project-relative-directory
</code>```

But this doesn't appear to work at all, not for absolute paths or relative paths; although it may be retrieved later via System.get, gradle doesn't appear to make use of it.

Are there any other solutions?

答:
When Gradle parses gradle.properties file, too much has already happened. So the only way to use a custom Gradle home is through a command line flag, which has the highest precedence, or through a system property.

Note that the documentation indicates that and does not mention the ability to set that value inside a properties file.

Body:
By default, gradle.user.home is set to ~/.gradle - I'd like to change it to a directory relative to the project, rather than the developer's home directory.

I know you can do so when you invoke gradle, like so:

$ gradle --gradle-user-home=./project-relative-directory

Or

$ gradle -Dgradle.user.home=./project-relative-directory

I know you can change the location of the build cache by adding the following to settings.gradle:

buildCache {
    local {
        // Set local build cache directory.
        directory = "${settingsDir}/build-cache"
    }
}

But gradle continues to use gradle.user.home for other caching.

The manual claims that you can specify gradle.user.home in gradle.properties, like so:

systemProp.gradle.user.home=./project-relative-directory

But this doesn't appear to work at all, not for absolute paths or relative paths; although it may be retrieved later via System.get, gradle doesn't appear to make use of it.

Are there any other solutions?


问:
Pytorch RuntimeError: [enforce fail at CPUAllocator.cpp:56] posix_memalign(&data, gAlignment, nbytes) == 0. 12 vs 0
I'm building a simple content based recommendations system. In order to compute the cosine similarity in a GPU accelerated way, i'm using Pytorch.

At the time of creating the tfidf vocabulary tensor from a csr_matrix, it promts the following RuntimeErrorr

RuntimeError: [enforce fail at CPUAllocator.cpp:56] posix_memalign(&data, gAlignment, nbytes) == 0. 12 vs 0

I'm doing it in this way:

```<code>coo = tfidf_matrix.tocoo()
values = coo.data
indices = np.vstack( (coo.row, coo.col ))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
tfidf_matrix_tensor = torch.sparse.FloatTensor(i, v, torch.Size(coo1.shape)).to_dense()
# Prompts the error
</code>```

I tried with a small test (tfidf matrix size = 10,296) dataset and it works.
The tfidf matrix size from the real dataset is (27639, 226957)

答: I tried the same piece of code that was throwing this error with the older version of PyTorch. It said that I need to have more RAM. Therefore, it's not a PyTorch bug. The only solution is to reduce matrix size somehow. </p>

Body:
I'm building a simple content based recommendations system. In order to compute the cosine similarity in a GPU accelerated way, i'm using Pytorch.

At the time of creating the tfidf vocabulary tensor from a csr_matrix, it promts the following RuntimeErrorr

RuntimeError: [enforce fail at CPUAllocator.cpp:56] posix_memalign(&data, gAlignment, nbytes) == 0. 12 vs 0

I'm doing it in this way:

coo = tfidf_matrix.tocoo()
values = coo.data
indices = np.vstack( (coo.row, coo.col ))
i = torch.LongTensor(indices)
v = torch.FloatTensor(values)
tfidf_matrix_tensor = torch.sparse.FloatTensor(i, v, torch.Size(coo1.shape)).to_dense()
# Prompts the error

I tried with a small test (tfidf matrix size = 10,296) dataset and it works.
The tfidf matrix size from the real dataset is (27639, 226957)


问:
Numerals font size to grow from small to big
I have a number=12345678, my expect output is first number font size is small then next number font size is bigger than first number and third number font size bigger than second number font size and so on.

How can I archive this using CSS or JS?

答:
Try

let n='12345678';

box.innerHTML= [...n].map((x,i)=>`<span style='font-size:${2*i+20}px'>${x}</span>`).join('');```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='box'></div></code>```

And pure CSS - but font low quality and number not lie on horizontal line

.num {
  margin-top:20px;
  transform: translateX(-13px) scaleX(1.35) perspective(100px) rotateY(-45deg);
  width:100px;
  line-height: 14px;
  font-size: 25px;
  /*background: red;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="num">12345678</div></code>```

Body:
Try

let n='12345678';

box.innerHTML= [...n].map((x,i)=>`<span style='font-size:${2*i+20}px'>${x}</span>`).join('');

<div id='box'></div>

And pure CSS - but font low quality and number not lie on horizontal line

.num {
  margin-top:20px;
  transform: translateX(-13px) scaleX(1.35) perspective(100px) rotateY(-45deg);
  width:100px;
  line-height: 14px;
  font-size: 25px;
  /*background: red;*/
}

<div class="num">12345678</div>


问:
Problems when creating a huge matrix
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

```<code>#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}
</code>```

Thanks in advance for all your help!

答:
1000000 rows and 100 columns is an awful lot of data (100 million of anything is going to take a lot of storage).  Perhaps you don't have enough memory?

Is every row and column populated?  If not, then you might be able to save something by using a sparse matrix representation.

Title: Problems when creating a huge matrix

Body:
I am trying to create a kind of table with random characters and writing the into a file, but I have a problem. The problem appears when I want to create huge tables. For example for a table with 10 rows x 5 columns everything is perfect, but for a table with 1.000.000 rows and 100 columns I have errors. Do you have any idea how could I solvent this problem???

I attached you the code I have created:

#include<iostream>
#include<fstream>
#include<stdio.h>
#include<string>
#include<ctime>
#include<sstream>

using namespace std;

int main()
{
    int rows, columns, rowsMax, columnsMax;
    int element1;
    char word[10];

    cout<<"Write the number of rows of your table: ";
    cin>>rowsMax;

    cout<<"Write the number of columns of your table: ";
    cin>>columnsMax;

    string matriz[100000][5]; // Here I write the number of row and columns that must be the same than the numbers introduced as input

    string table ("Table1");

    ofstream myfile (table);
    if(myfile.is_open())
    srand(1);
    for(rows=0;rows<rowsMax;rows++)
    {
        for(columns=0;columns<columnsMax;columns++)
        {
            element1 = rand() % 100000 + 1;

            int len = rand () % 4 + 4;
            word [len] = 0;
            while (len) word [--len] = 'A' + rand () % 58;

            myfile<<element1<<word;
            myfile<<"|";

            std::stringstream ss;
            ss<<element1;

            string mat;
            mat +=ss.str();
            mat +=word;
            matriz[rows][columns]= mat;
        }
        myfile<<endl;

    }
    myfile.close();

    system("pause");
    return 0;

}

Thanks in advance for all your help!


问:
JTable change selection without flickering ui
I want to change the selection in a JTable. A typical approach is to clear and re-select as suggested here:

```<code>ListSelectionModel model = table.getSelectionModel();
model.clearSelection();
model.addSelectionInterval(1, 1);
model.addSelectionInterval(18, 18);
</code>```

Sadly, clearSelection updates the UI immediately. Thus, if you step through this code, the selection is gone and then back again, which potentially results in flickering.

I tried to prevent the UI from updating by ignoring the change. However, the following does not work:

```<code>model.setValueIsAdjusting( true );
model.clearSelection();
model.setValueIsAdjusting( false );
</code>```

It seems the flag is ignored in the UI. Also removing and re-adding the ListSelectionListeners before, respectively after the clearSelection did not work. The UI is still updated and potentially flickers.

Is there a better approach to change the complete selection of a JTable with multiple rows, possibly not in a continuous selection?

For me this is not a major problem because you really need to look for the flickering. Nonetheless, it is not optimal.

答:
The problem occurs only if you are not on the Event Dispatch Thread (EDT). Kudos to Sascha for the hint.

Example:

```<code>import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

public class JTableExample extends JFrame
{
    private static final long serialVersionUID = 1L;

    private final JTable table;

    public JTableExample()
    {
        // headers and data for the table
        final String[] columns = new String[]{"Id", "Name"};
        final Object[][] data = new Object[][]{{1, "Alice"}, {2, "Bob"}, {3, "Charlie"},};

        // create table with data
        table = new JTable( data, columns );
        this.add( new JScrollPane( table ) );

        // Add key listener to trigger re-selection of columns
        table.addKeyListener( new KeyAdapter()
        {
            @Override
            public void keyReleased( final KeyEvent e )
            {
                // Re-select on event dispatch thread (EDT)
                if( e.getKeyCode() == KeyEvent.VK_1 )
                {
                    reselectTable();
                }

                // Re-select on a thread that is not the EDT
                if( e.getKeyCode() == KeyEvent.VK_2 )
                {
                    new Thread( () -> reselectTable() ).start();
                }

                // Re-select on a thread that is not the EDT, but using invokeLater to get back to the EDT
                if( e.getKeyCode() == KeyEvent.VK_3 )
                {
                    new Thread( () -> SwingUtilities.invokeLater( () -> reselectTable() ) ).start();
                }
            }
        } );

        // Setup JFrame
        setTitle( "JTable Example" );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        pack();
        setVisible( true );
    }

    public static void main( final String[] args )
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                new JTableExample();
            }
        } );
    }

    private void reselectTable()
    {
        System.out.println( "isEventDispatchThread:" + SwingUtilities.isEventDispatchThread() );

        final ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.clearSelection();
        // PUT BREAKPOINT HERE
        // Selection in rendered GUI is gone here when not in the EDT
        selectionModel.addSelectionInterval( 0, 0 );
        selectionModel.addSelectionInterval( 2, 2 );
    }
}
</code>```

Body:
I want to change the selection in a JTable. A typical approach is to clear and re-select as suggested here:

ListSelectionModel model = table.getSelectionModel();
model.clearSelection();
model.addSelectionInterval(1, 1);
model.addSelectionInterval(18, 18);

Sadly, clearSelection updates the UI immediately. Thus, if you step through this code, the selection is gone and then back again, which potentially results in flickering.

I tried to prevent the UI from updating by ignoring the change. However, the following does not work:

model.setValueIsAdjusting( true );
model.clearSelection();
model.setValueIsAdjusting( false );

It seems the flag is ignored in the UI. Also removing and re-adding the ListSelectionListeners before, respectively after the clearSelection did not work. The UI is still updated and potentially flickers.

Is there a better approach to change the complete selection of a JTable with multiple rows, possibly not in a continuous selection?

For me this is not a major problem because you really need to look for the flickering. Nonetheless, it is not optimal.

Body:
The problem occurs only if you are not on the Event Dispatch Thread (EDT). Kudos to Sascha for the hint.

Example:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

public class JTableExample extends JFrame
{
    private static final long serialVersionUID = 1L;

    private final JTable table;

    public JTableExample()
    {
        // headers and data for the table
        final String[] columns = new String[]{"Id", "Name"};
        final Object[][] data = new Object[][]{{1, "Alice"}, {2, "Bob"}, {3, "Charlie"},};

        // create table with data
        table = new JTable( data, columns );
        this.add( new JScrollPane( table ) );

        // Add key listener to trigger re-selection of columns
        table.addKeyListener( new KeyAdapter()
        {
            @Override
            public void keyReleased( final KeyEvent e )
            {
                // Re-select on event dispatch thread (EDT)
                if( e.getKeyCode() == KeyEvent.VK_1 )
                {
                    reselectTable();
                }

                // Re-select on a thread that is not the EDT
                if( e.getKeyCode() == KeyEvent.VK_2 )
                {
                    new Thread( () -> reselectTable() ).start();
                }

                // Re-select on a thread that is not the EDT, but using invokeLater to get back to the EDT
                if( e.getKeyCode() == KeyEvent.VK_3 )
                {
                    new Thread( () -> SwingUtilities.invokeLater( () -> reselectTable() ) ).start();
                }
            }
        } );

        // Setup JFrame
        setTitle( "JTable Example" );
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        pack();
        setVisible( true );
    }

    public static void main( final String[] args )
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            @Override
            public void run()
            {
                new JTableExample();
            }
        } );
    }

    private void reselectTable()
    {
        System.out.println( "isEventDispatchThread:" + SwingUtilities.isEventDispatchThread() );

        final ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.clearSelection();
        // PUT BREAKPOINT HERE
        // Selection in rendered GUI is gone here when not in the EDT
        selectionModel.addSelectionInterval( 0, 0 );
        selectionModel.addSelectionInterval( 2, 2 );
    }
}


问:
ion-select set start value
I am trying to set the initial data displayed for an Ion-select.
I have narrowed it down to this simplest example although I have it in another situation too. Most of the questions here seem to be using [ngModel] which I don't think I need because I am using an Angular Reactive form.
The html is:

```<code>  <form [formGroup]="userDetailsForm" (ngSubmit)="onSubmit()">

 ... some stuff
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select placeholder="Select One" formControlName="Gender">
    <ion-select-option value="3">Female</ion-select-option>
    <ion-select-option value="2">Male</ion-select-option>
    <ion-select-option value="1">Other</ion-select-option>
    <ion-select-option value="0">Prefer Not to Say</ion-select-option>
 </ion-select>
</ion-item>

 ... more stuff
<ion-button expand="full" type="submit">Submit</ion-button>

</form>
</code>```

My code is:

```<code>  ngOnInit() {

    this.userDetailsForm = this.formBuilder.group({
    ... some stuff
     Gender: [],
    });
    this.userService.getUserServer().subscribe (user => {
      // console.log('Patching the form');
      this.userDetailsForm.patchValue(user);
      ... other irrelevant code
    },
      error => this.helper.showAlert('We cant connect to the server at the moment msg is:' + error)
    );

  }
</code>```

The field is always showing empty (with the placeholder as shown), and I have also tried removing the placeholder and using:

```<code>      <ion-select value ="3" formControlName="Gender">
</code>```

No matter what I try it won't show the default or what I set it to...
Sorry if this is obvious but what am I missing?
Many thanks.

EDIT
I have tried removing the formControlName="Gender" part of it and now it works. Except of course it won't be part of the reactive form... I think this smells a bit buggy - I will continue to dig, meanwhile, any further thoughts welcome.

答:
You can try to add already selected empty option with your placeholder:      </p>

```<code><ion-select formControlName="Gender">
            <ion-select-option value="" selected="selected" hidden="hidden">Choose here</ion-select-option>
            <ion-select-option value="3">Female</ion-select-option>
            <ion-select-option value="2">Male</ion-select-option>
            <ion-select-option value="1">Other</ion-select-option>
            <ion-select-option value="0">Prefer Not to Say</ion-select-option>
</ion-select>
</code>```

Title: ion-select set start value

Body:
I am trying to set the initial data displayed for an Ion-select.
I have narrowed it down to this simplest example although I have it in another situation too. Most of the questions here seem to be using [ngModel] which I don't think I need because I am using an Angular Reactive form.
The html is:

  <form [formGroup]="userDetailsForm" (ngSubmit)="onSubmit()">

 ... some stuff
<ion-item>
  <ion-label>Gender</ion-label>
  <ion-select placeholder="Select One" formControlName="Gender">
    <ion-select-option value="3">Female</ion-select-option>
    <ion-select-option value="2">Male</ion-select-option>
    <ion-select-option value="1">Other</ion-select-option>
    <ion-select-option value="0">Prefer Not to Say</ion-select-option>
 </ion-select>
</ion-item>

 ... more stuff
<ion-button expand="full" type="submit">Submit</ion-button>

</form>

My code is:

  ngOnInit() {

    this.userDetailsForm = this.formBuilder.group({
    ... some stuff
     Gender: [],
    });
    this.userService.getUserServer().subscribe (user => {
      // console.log('Patching the form');
      this.userDetailsForm.patchValue(user);
      ... other irrelevant code
    },
      error => this.helper.showAlert('We cant connect to the server at the moment msg is:' + error)
    );

  }

The field is always showing empty (with the placeholder as shown), and I have also tried removing the placeholder and using:

      <ion-select value ="3" formControlName="Gender">

No matter what I try it won't show the default or what I set it to...
Sorry if this is obvious but what am I missing?
Many thanks.

EDIT
I have tried removing the formControlName="Gender" part of it and now it works. Except of course it won't be part of the reactive form... I think this smells a bit buggy - I will continue to dig, meanwhile, any further thoughts welcome.

Body:
You can try to add already selected empty option with your placeholder:

<ion-select formControlName="Gender">
            <ion-select-option value="" selected="selected" hidden="hidden">Choose here</ion-select-option>
            <ion-select-option value="3">Female</ion-select-option>
            <ion-select-option value="2">Male</ion-select-option>
            <ion-select-option value="1">Other</ion-select-option>
            <ion-select-option value="0">Prefer Not to Say</ion-select-option>
</ion-select>


问:
How to execute single sql query in multiple databases
I have cloud server where I've hosted a web application for my customers. Each customer has a different SQL database and website in IIS. Whenever I want to execute a sql query to update something, I have to do this manually in each database. There are almost 50 databases and it takes around an hour in executing single query each time. Can someone provide me a tool or way by which I just select all the database at once and execute that query simply?</p>

答:
If I guess you have all databases are in same structure and every time you run script to update something, the script basically same and you just run that same script one by one for each customer.

If the above case is true, you can use CURSOR to produce a Loop between your all databases and Execute necessary script to serve your purpose.

Note: This is not the solution, Just Idea.

```<code>--The first step will be creating a Table variable
--where you will INSERT all your database names
--for a further loop as below-

DECLARE @DbName VARCHAR(200)
DECLARE @DatabaseList TABLE (DbName VARCHAR(200))

INSERT INTO @DatabaseList (DbName) VALUES('db_name_1')
INSERT INTO @DatabaseList (DbName) VALUES('db_name_2')
--.......................
INSERT INTO @DatabaseList (DbName) VALUES('db_name_50')

--Now you can use CURSOR to generate the loop
--and execute your required script as shown below

DECLARE db_cursor CURSOR FOR
SELECT DbName FROM @DatabaseList

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DbName

WHILE @@FETCH_STATUS = 0
BEGIN

    --HERE You need to write your script That you
    --Execute for all your database. I have added
    --a sample script where I guess you updating
    --certain tables in your all database WHERE ID = 1

    -- You can see the Database Name inserted in the
    -- Script Dynamically from the Loop

    EXEC ('UPDATE '+@DbName+'.dbo.<Your_table_Name_Here>
           WHERE ID=1')

    --END OF Dynamic Part

    FETCH NEXT FROM db_cursor INTO @DbName
END

CLOSE db_cursor
DEALLOCATE db_cursor
</code>```

Body:
If I guess you have all databases are in same structure and every time you run script to update something, the script basically same and you just run that same script one by one for each customer.

If the above case is true, you can use CURSOR to produce a Loop between your all databases and Execute necessary script to serve your purpose.

Note: This is not the solution, Just Idea.

--The first step will be creating a Table variable
--where you will INSERT all your database names
--for a further loop as below-

DECLARE @DbName VARCHAR(200)
DECLARE @DatabaseList TABLE (DbName VARCHAR(200))

INSERT INTO @DatabaseList (DbName) VALUES('db_name_1')
INSERT INTO @DatabaseList (DbName) VALUES('db_name_2')
--.......................
INSERT INTO @DatabaseList (DbName) VALUES('db_name_50')

--Now you can use CURSOR to generate the loop
--and execute your required script as shown below

DECLARE db_cursor CURSOR FOR
SELECT DbName FROM @DatabaseList

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @DbName

WHILE @@FETCH_STATUS = 0
BEGIN

    --HERE You need to write your script That you
    --Execute for all your database. I have added
    --a sample script where I guess you updating
    --certain tables in your all database WHERE ID = 1

    -- You can see the Database Name inserted in the
    -- Script Dynamically from the Loop

    EXEC ('UPDATE '+@DbName+'.dbo.<Your_table_Name_Here>
           WHERE ID=1')

    --END OF Dynamic Part

    FETCH NEXT FROM db_cursor INTO @DbName
END

CLOSE db_cursor
DEALLOCATE db_cursor


问:
Could not find a package configuration file provided by "Qt5Svg"
I tried to install some disassembler using

```<code>$sudo cmake ../edb-debugger-master
</code>```

but it's giving me an following error

```<code>-- Boost version: 1.58.0
-- Checking for module 'libgvc>=2.38.0'
--
CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt5/Qt5Config.cmake:26 (find_package):
Could not find a package configuration file provided by "Qt5Svg" with any
of the following names:
Qt5SvgConfig.cmake
qt5svg-config.cmake
Add the installation prefix of "Qt5Svg" to CMAKE_PREFIX_PATH or set
"Qt5Svg_DIR" to a directory containing one of the above files. If "Qt5Svg"
provides a separate development package or SDK, be sure it has been
installed.
Call Stack (most recent call first):
src/CMakeLists.txt:26 (find_package)
-- Configuring incomplete, errors occurred!
See also "/home/kanna/Desktop/build/CMakeFiles/CMakeOutput.log".
</code>```

If you take a look at this picture, you can see both Qt5 (dependency for this software) and Qt5SvgConfig.cmake are present.

Then why is it still giving me an error?

答:
It has been solved on my side with:</p>

```<code>sudo apt install libqt5svg5-dev
</code>```

Body:
I tried to install some disassembler using

$sudo cmake ../edb-debugger-master

but it's giving me an following error

-- Boost version: 1.58.0
-- Checking for module 'libgvc>=2.38.0'
--
CMake Error at /usr/lib/x86_64-linux-gnu/cmake/Qt5/Qt5Config.cmake:26 (find_package):
Could not find a package configuration file provided by "Qt5Svg" with any
of the following names:
Qt5SvgConfig.cmake
qt5svg-config.cmake
Add the installation prefix of "Qt5Svg" to CMAKE_PREFIX_PATH or set
"Qt5Svg_DIR" to a directory containing one of the above files. If "Qt5Svg"
provides a separate development package or SDK, be sure it has been
installed.
Call Stack (most recent call first):
src/CMakeLists.txt:26 (find_package)
-- Configuring incomplete, errors occurred!
See also "/home/kanna/Desktop/build/CMakeFiles/CMakeOutput.log".

If you take a look at this picture, you can see both Qt5 (dependency for this software) and Qt5SvgConfig.cmake are present.

Then why is it still giving me an error?

Body:
It has been solved on my side with:

sudo apt install libqt5svg5-dev


问:
Connecting to SQL Server using windows authentication
When I was trying to connect to SQL Server using the following code:

```<code>SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";
</code>```

I get the following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)

答:
This worked for me:

in web.config file;

```<code><add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>
</code>```

Body:
When I was trying to connect to SQL Server using the following code:

SqlConnection con = new SqlConnection("Server=localhost,Authentication=Windows Authentication, Database=employeedetails");
con.Open();
SqlCommand cmd;
string s = "delete employee where empid=103";

I get the following error:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)

Body:
This worked for me:

in web.config file;

<add name="connectionstring name " connectionstring="server=SQLserver name; database= databasename; integrated security = true"/>


问:
How to check whether firebug is installed in Mozilla or not?

Possible Duplicate:

  Javascript that detects Firebug?

How to check whether Firebug is installed in Mozilla or not using JavaScript code?

答:
The accepted answer doesn’t detect Firebug at all, it just detects if a console object is available.

If you want to detect Firebug, look for window.console.firebug. Use this snippet:

```<code>if (window.console && console.firebug) {
  // Firebug is enabled
}
</code>```

Body:
The accepted answer doesn’t detect Firebug at all, it just detects if a console object is available.

If you want to detect Firebug, look for window.console.firebug. Use this snippet:

if (window.console && console.firebug) {
  // Firebug is enabled
}


问:
Inherited class object not showing base class method
I'd like to put in a base class a method in order not to repeat it in the inherited classes. There are interfaces for the base class and the inherited classes. Once I create a inherited class object I cannot use the base class method that I want to use. ¿What's wrong?

Thanks in advance.

```<code>public interface IRepository
{
    string GetError(string LogNumber);
}

public class Repository : IRepository
{
    public Repository()
    {
    }

    public string GetError(string LogNumber)
    {
        return "The error is " + LogNumber;
    }
}

public interface ICustomerRepository
{
    // READ
    List<Customer> ReadAll();

}

public class CustomerRepository : Repository, ICustomerRepository
{
    public CustomerRepository() : base()
    {
    }

    public List<Customer> ReadAll()
    {
        return fooFunction();
    }
}

CustomerRepository myRepository = new CustomerRepository()
myRepository.
</code>```

答:
I think your code working fine. Please check below solution</p>

```<code> public Form1()
        {
            InitializeComponent();
            CustomerRepository myRepository = new CustomerRepository();
            myRepository.GetError("string error");

        }
        public interface IRepository
        {
            string GetError(string LogNumber);
        }

        public class Repository : IRepository
        {
            public Repository()
            {
            }

            public string GetError(string LogNumber)
            {
                return "The error is " + LogNumber;
            }
        }

        public interface ICustomerRepository
        {
            // READ
            List<Customer> ReadAll();

        }

        public class CustomerRepository : Repository, ICustomerRepository
        {
            public CustomerRepository() : base()
            {
            }

            public List<Customer> ReadAll()
            {
                List<Customer> list;
                return list = new List<Customer>();
            }
        }

        public class Customer
        {
        }
</code>```

Body:
I'd like to put in a base class a method in order not to repeat it in the inherited classes. There are interfaces for the base class and the inherited classes. Once I create a inherited class object I cannot use the base class method that I want to use. ¿What's wrong?

Thanks in advance.

public interface IRepository
{
    string GetError(string LogNumber);
}

public class Repository : IRepository
{
    public Repository()
    {
    }

    public string GetError(string LogNumber)
    {
        return "The error is " + LogNumber;
    }
}

public interface ICustomerRepository
{
    // READ
    List<Customer> ReadAll();

}

public class CustomerRepository : Repository, ICustomerRepository
{
    public CustomerRepository() : base()
    {
    }

    public List<Customer> ReadAll()
    {
        return fooFunction();
    }
}

CustomerRepository myRepository = new CustomerRepository()
myRepository.

Body:
I think your code working fine. Please check below solution

 public Form1()
        {
            InitializeComponent();
            CustomerRepository myRepository = new CustomerRepository();
            myRepository.GetError("string error");

        }
        public interface IRepository
        {
            string GetError(string LogNumber);
        }

        public class Repository : IRepository
        {
            public Repository()
            {
            }

            public string GetError(string LogNumber)
            {
                return "The error is " + LogNumber;
            }
        }

        public interface ICustomerRepository
        {
            // READ
            List<Customer> ReadAll();

        }

        public class CustomerRepository : Repository, ICustomerRepository
        {
            public CustomerRepository() : base()
            {
            }

            public List<Customer> ReadAll()
            {
                List<Customer> list;
                return list = new List<Customer>();
            }
        }

        public class Customer
        {
        }


问:
Find inactive GameObject by name, tag or layer
First, I need to deactivate a game object and then after 10 seconds, activate it, so I thought coroutines are suitable:

```<code>IEnumerator BarDeactivate(float sec)
{
        yield return new WaitForSeconds(sec);

        var obj = GameObject.Find("OBJ");
        obj.SetActive(false);
}

IEnumerator BarReactivate(float sec)
{
        yield return new WaitForSeconds(sec);

        var obj = transform.Find("OBJ");
        obj.SetActive(true);
}
</code>```

Obviously, I can no longer use GameObject.Find so I use transform.Find to find the inactive game object, but of course .SetActive now does not work, since obj is not actually a game object...

How do I cast the found transform, so that it can be set active again?

I tried obj.gameObject.SetActive(true) but it must be wrong, because the object would not come back to life...

答: I have this issue with ARCore, Vuforia, etc. because GameObjects are not alive until they can be tracked. One way is wait for the target to be recognized and then look for the GameObjects, but if they are manually inactive the only other (uncomplicated?) way would be to manually list them and link them as a public array with the script. If your script is linked then even an inactive GameObject will be accessible.</p>

Body:
First, I need to deactivate a game object and then after 10 seconds, activate it, so I thought coroutines are suitable:

IEnumerator BarDeactivate(float sec)
{
        yield return new WaitForSeconds(sec);

        var obj = GameObject.Find("OBJ");
        obj.SetActive(false);
}

IEnumerator BarReactivate(float sec)
{
        yield return new WaitForSeconds(sec);

        var obj = transform.Find("OBJ");
        obj.SetActive(true);
}

Obviously, I can no longer use GameObject.Find so I use transform.Find to find the inactive game object, but of course .SetActive now does not work, since obj is not actually a game object...

How do I cast the found transform, so that it can be set active again?

I tried obj.gameObject.SetActive(true) but it must be wrong, because the object would not come back to life...