问:
Code looping when I don't need it to, hard to explain in title
I'm trying to make a progress checklist for the game Final Fantasy X-2.

What I have is this:

The Label names "Luca - +1.6" is label1. Under that is CheckedListBox1, then Label2, CheckedListBox2 and so on.

What should happen is, when every item in a CheckedListBox (CLB for short) is
checked, the CLB and Label above should have it's font changed to strikeout
and trim the Label.Text to just the number and add that to the TabPage1.Text.

The problem I have is this: I check both item is CLB1, the CLB and label get struckout, and TabPage1.Text is changed to "Chapter 1 - 1.6". Now when I check ONE item in CLB2, 1.6 get added to TabPage1.Text making it 3.2. That repeats with every item I check.

I think I know whats causing the problem, but I'm not sure how to go about fixing it. I would like to keep the code condensed, and not have say 20 If statements for each CLB.

My code is below and an image is linked.

Form Image

```<code>Private Sub CheckedListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged, CheckedListBox2.SelectedIndexChanged
    Dim CLmatches() As Control
    Dim LBmatches() As Control
    For a As Integer = 1 To TabPage1.Controls.Count
        CLmatches = Me.Controls.Find("CheckedListBox" & a, True)
        If CLmatches.Length > 0 AndAlso TypeOf CLmatches(0) Is CheckedListBox Then
            Dim cl As CheckedListBox = DirectCast(CLmatches(0), CheckedListBox)
            If cl.CheckedItems.Count = cl.Items.Count Then
                'CheckBox1.Checked = True
                cl.Font = New Font(cl.Font, cl.Font.Style Or FontStyle.Strikeout)
                LBmatches = Me.Controls.Find("Label" & a, True)
                If LBmatches.Length > 0 AndAlso TypeOf LBmatches(0) Is Label Then
                    Dim lb = DirectCast(LBmatches(0), Label)
                    lb.Font = New Font(lb.Font, lb.Font.Style Or FontStyle.Strikeout)
                    Dim test As String = lb.Text
                    Dim phrase As String = test.Substring(test.IndexOf("+"c) + 1)
                    percentage += phrase
                    TabPage1.Text = "Chapter 1 - " & percentage & "%"
                End If
            End If
        End If
    Next
End Sub
End Class
</code>```

答:
Another bug caused by global variables (and a classic one)

You should set the global variable percentage to zero before starting any of this code. If you click more than one time on the CheckedListBoxes your percentage always increases from the value calculated in the previous event at this line

```<code>percentage += phrase
</code>```

regardless of what the other checkedlistbox status is.

Also you should set the TabPage1.Text just one time before exiting from the event handler.

```<code>Private Sub CheckedListBox1_SelectedIndexChanged(.....)....

    Dim CLmatches() As Control
    Dim LBmatches() As Control
    percentage = 0
    For a As Integer = 1 To TabPage1.Controls.Count
       .....
    Next
    TabPage1.Text = "Chapter 1 - " & percentage & "%"
End Sub
</code>```

In this mode the calc is always correct even if you uncheck some of your checkeditems

A point that is not possible to answer now is if you really need this variable to be a global class level one. If possible try to avoid global class variables.

Body:
I'm trying to make a progress checklist for the game Final Fantasy X-2.

What I have is this:

The Label names "Luca - +1.6" is label1. Under that is CheckedListBox1, then Label2, CheckedListBox2 and so on.

What should happen is, when every item in a CheckedListBox (CLB for short) is
checked, the CLB and Label above should have it's font changed to strikeout
and trim the Label.Text to just the number and add that to the TabPage1.Text.

The problem I have is this: I check both item is CLB1, the CLB and label get struckout, and TabPage1.Text is changed to "Chapter 1 - 1.6". Now when I check ONE item in CLB2, 1.6 get added to TabPage1.Text making it 3.2. That repeats with every item I check.

I think I know whats causing the problem, but I'm not sure how to go about fixing it. I would like to keep the code condensed, and not have say 20 If statements for each CLB.

My code is below and an image is linked.

Form Image

Private Sub CheckedListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CheckedListBox1.SelectedIndexChanged, CheckedListBox2.SelectedIndexChanged
    Dim CLmatches() As Control
    Dim LBmatches() As Control
    For a As Integer = 1 To TabPage1.Controls.Count
        CLmatches = Me.Controls.Find("CheckedListBox" & a, True)
        If CLmatches.Length > 0 AndAlso TypeOf CLmatches(0) Is CheckedListBox Then
            Dim cl As CheckedListBox = DirectCast(CLmatches(0), CheckedListBox)
            If cl.CheckedItems.Count = cl.Items.Count Then
                'CheckBox1.Checked = True
                cl.Font = New Font(cl.Font, cl.Font.Style Or FontStyle.Strikeout)
                LBmatches = Me.Controls.Find("Label" & a, True)
                If LBmatches.Length > 0 AndAlso TypeOf LBmatches(0) Is Label Then
                    Dim lb = DirectCast(LBmatches(0), Label)
                    lb.Font = New Font(lb.Font, lb.Font.Style Or FontStyle.Strikeout)
                    Dim test As String = lb.Text
                    Dim phrase As String = test.Substring(test.IndexOf("+"c) + 1)
                    percentage += phrase
                    TabPage1.Text = "Chapter 1 - " & percentage & "%"
                End If
            End If
        End If
    Next
End Sub
End Class

Body:
Another bug caused by global variables (and a classic one)

You should set the global variable percentage to zero before starting any of this code. If you click more than one time on the CheckedListBoxes your percentage always increases from the value calculated in the previous event at this line

percentage += phrase

regardless of what the other checkedlistbox status is.

Also you should set the TabPage1.Text just one time before exiting from the event handler.

Private Sub CheckedListBox1_SelectedIndexChanged(.....)....

    Dim CLmatches() As Control
    Dim LBmatches() As Control
    percentage = 0
    For a As Integer = 1 To TabPage1.Controls.Count
       .....
    Next
    TabPage1.Text = "Chapter 1 - " & percentage & "%"
End Sub

In this mode the calc is always correct even if you uncheck some of your checkeditems

A point that is not possible to answer now is if you really need this variable to be a global class level one. If possible try to avoid global class variables.


来源: stackexchange

问:
Control Flexslider from outside element.
I have a Flexislider that I would like to control from outside the element. I tried this:

```<code>var myslider = $('.slider').flexslider({
    animation: 'slide'
});

$('button').click(function () {
    myslider.flexAnimate(3)    //Function: Move slider - (target, pause) parameters
});
</code>```

But that returns TypeError: Object [object Object] has no method 'flexAnimate'

Then I stumbled upon this thread (https://github.com/woothemes/FlexSlider/issues/125) which indicates this is the proper method:

```<code>$('button').click(function () {
    myslider.flexslider(3)
});
</code>```

However I don't see how I can specify the speed of the animation. I want the change to be instant for that event only.

I guess I'm wondering how one accesses the slider API as mentioned in the docs from outside the slider element

```<code>slider                        //Object: The slider element itself
slider.container              //Object: The ul.slides within the slider
slider.slides                 //Object: The slides of the slider
slider.count                  //Int: The total number of slides in the slider
slider.currentSlide           //Int: The slide currently being shown
slider.animatingTo            //Int: Useful in .before(), the slide currently animating to
slider.animating              //Boolean: is slider animating?
slider.atEnd                  //Boolean: is the slider at either end?
slider.manualPause            //Boolean: force slider to stay paused during pauseOnHover event
slider.controlNav             //Object: The slider controlNav
slider.directionNav           //Object: The slider directionNav
slider.controlsContainer      //Object: The controlsContainer element of the slider
slider.manualControls         //Object: The manualControls element of the slider
slider.flexAnimate(target)    //Function: Move slider - (target, pause) parameters
slider.pause()                //Function: Pause slider slideshow interval
slider.resume()               //Function: Resume slider slideshow interval
slider.canAdvance(target)     //Function: returns boolean if slider can advance - (target) parameter
slider.getTarget(dir)         //Function: get target given a direction - "next" or "prev" parameter
</code>```

答:
You can try setting the slider object first:

```<code>$slider = $('.slideshow').flexslider();
</code>```

then use flexslider's public methods:

```<code>$slider.data('flexslider').pause();
$slider.data('flexslider').play();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a Flexislider that I would like to control from outside the element. I tried this:

var myslider = $('.slider').flexslider({
    animation: 'slide'
});

$('button').click(function () {
    myslider.flexAnimate(3)    //Function: Move slider - (target, pause) parameters
});

But that returns TypeError: Object [object Object] has no method 'flexAnimate'

Then I stumbled upon this thread (https://github.com/woothemes/FlexSlider/issues/125) which indicates this is the proper method:

$('button').click(function () {
    myslider.flexslider(3)
});

However I don't see how I can specify the speed of the animation. I want the change to be instant for that event only.

I guess I'm wondering how one accesses the slider API as mentioned in the docs from outside the slider element

slider                        //Object: The slider element itself
slider.container              //Object: The ul.slides within the slider
slider.slides                 //Object: The slides of the slider
slider.count                  //Int: The total number of slides in the slider
slider.currentSlide           //Int: The slide currently being shown
slider.animatingTo            //Int: Useful in .before(), the slide currently animating to
slider.animating              //Boolean: is slider animating?
slider.atEnd                  //Boolean: is the slider at either end?
slider.manualPause            //Boolean: force slider to stay paused during pauseOnHover event
slider.controlNav             //Object: The slider controlNav
slider.directionNav           //Object: The slider directionNav
slider.controlsContainer      //Object: The controlsContainer element of the slider
slider.manualControls         //Object: The manualControls element of the slider
slider.flexAnimate(target)    //Function: Move slider - (target, pause) parameters
slider.pause()                //Function: Pause slider slideshow interval
slider.resume()               //Function: Resume slider slideshow interval
slider.canAdvance(target)     //Function: returns boolean if slider can advance - (target) parameter
slider.getTarget(dir)         //Function: get target given a direction - "next" or "prev" parameter

Body:
You can try setting the slider object first:

$slider = $('.slideshow').flexslider();

then use flexslider's public methods:

$slider.data('flexslider').pause();
$slider.data('flexslider').play();


问:
Storing multiple image paths in one column of MySQL database table
I'm able to upload multiple images to the upload folder and its path to the database but my code is creating new row in database for each image with new id (which i dont want). I want to store all the images path to a single column in database with same id and separated with comma.

here is my php code:

```<code>    <?php
    include('connection.php');
    foreach($_FILES['files']['name'] as $i => $name) {

    $name = $_FILES['files']['name'][$i];
    $size = $_FILES['files']['size'][$i];
    $type = $_FILES['files']['type'][$i];
    $tmp = $_FILES['files']['tmp_name'][$i];

    $explode = explode('.', $name);

    $ext = end($explode);

    $path = 'uploads/';
    $path = $path . basename( $explode[0] . time() .'.'. $ext);

     $sql="INSERT into pictures (FILE_NAME, FILE_SIZE, FILE_TYPE )
     VALUES('$name','$size','$type'); ";

    mysqli_query($conn, $sql);
    $errors = array();

    if(empty($_FILES['files']['tmp_name'][$i])) {
        $errors[] = 'Please choose at least 1 file to be uploaded.';
    }else {

        $allowed = array('jpg','jpeg','gif','bmp','png');

        $max_size = 2000000; // 2MB

        if(in_array($ext, $allowed) === false) {
            $errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
        }

        if($size > $max_size) {
            $errors[] = 'The file <b>'.$name.'</b> size is too hight.';
        }

    }

    if(empty($errors)) {

        if(!file_exists('uploads')) {
            mkdir('uploads', 0777);
        }

        if(move_uploaded_file($tmp, $path)) {
            echo '<p>The file <b>'.$name.'</b> successful upload</p>';
        }else {
            echo 'Something went wrong while uploading
     <b>'.$name.'</b>';
        }

    }else {
        foreach($errors as $error) {
            echo '<p>'.$error.'<p>';
        }
    }

}

    ?>
</code>```

database screenshot as below

答:
Just improve your code and also place insert query outside the foreach loop

```<code><?php
include('connection.php');
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {

    $name = $_FILES['files']['name'][$i];
    $size = $_FILES['files']['size'][$i];
    $type = $_FILES['files']['type'][$i];
    $tmp = $_FILES['files']['tmp_name'][$i];

    $explode = explode('.', $name);

    $ext = end($explode);

    $updatdName = $explode[0] . time() .'.'. $ext;
    $path = 'uploads/';
    $path = $path . basename( $updatdName );

    if(empty($_FILES['files']['tmp_name'][$i])) {
        $errors[] = 'Please choose at least 1 file to be uploaded.';
    }else {

        $allowed = array('jpg','jpeg','gif','bmp','png');

        $max_size = 2000000; // 2MB

        if(in_array($ext, $allowed) === false) {
            $errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
        }

        if($size > $max_size) {
            $errors[] = 'The file <b>'.$name.'</b> size is too hight.';
        }

    }

    if(empty($errors)) {

        // if there is no error then set values
        $files['file_name'][] = $updatdName;
        $files['size'][] = $size;
        $files['type'][] = $type;
        $errors = array();
        if(!file_exists('uploads')) {
            mkdir('uploads', 0777);
        }

        if(move_uploaded_file($tmp, $path)) {
            echo '<p>The file <b>'.$name.'</b> successful upload</p>';
        }else {
            echo 'Something went wrong while uploading
     <b>'.$name.'</b>';
        }

    }else {
        foreach($errors as $error) {
            echo '<p>'.$error.'<p>';
        }
    }

}

if(!empty($files)) {

    $files['file_name'][] = $updatdName;
    $files['size'][] = $size;
    $files['type'][] = $type;
    $names = implode(',', $files['file_name']);
    $sizes = implode(',', $files['size']);
    $types = implode(',', $files['type']);
    $sql="INSERT into pictures (FILE_NAME, FILE_SIZE, FILE_TYPE )
         VALUES('$names','$sizes','$types'); ";
    mysqli_query($conn, $sql);
}
</code>```

I think this will help you.

Body:
I'm able to upload multiple images to the upload folder and its path to the database but my code is creating new row in database for each image with new id (which i dont want). I want to store all the images path to a single column in database with same id and separated with comma.

here is my php code:

    <?php
    include('connection.php');
    foreach($_FILES['files']['name'] as $i => $name) {

    $name = $_FILES['files']['name'][$i];
    $size = $_FILES['files']['size'][$i];
    $type = $_FILES['files']['type'][$i];
    $tmp = $_FILES['files']['tmp_name'][$i];

    $explode = explode('.', $name);

    $ext = end($explode);

    $path = 'uploads/';
    $path = $path . basename( $explode[0] . time() .'.'. $ext);

     $sql="INSERT into pictures (FILE_NAME, FILE_SIZE, FILE_TYPE )
     VALUES('$name','$size','$type'); ";

    mysqli_query($conn, $sql);
    $errors = array();

    if(empty($_FILES['files']['tmp_name'][$i])) {
        $errors[] = 'Please choose at least 1 file to be uploaded.';
    }else {

        $allowed = array('jpg','jpeg','gif','bmp','png');

        $max_size = 2000000; // 2MB

        if(in_array($ext, $allowed) === false) {
            $errors[] = 'The file '.$name.' extension is not allowed.';
        }

        if($size > $max_size) {
            $errors[] = 'The file '.$name.' size is too hight.';
        }

    }

    if(empty($errors)) {

        if(!file_exists('uploads')) {
            mkdir('uploads', 0777);
        }

        if(move_uploaded_file($tmp, $path)) {
            echo '
The file '.$name.' successful upload
';
        }else {
            echo 'Something went wrong while uploading
     '.$name.'';
        }

    }else {
        foreach($errors as $error) {
            echo '
'.$error.'
';
        }
    }

}

    ?>

database screenshot as below

Body:
Just improve your code and also place insert query outside the foreach loop

<?php
include('connection.php');
$files = [];
foreach($_FILES['files']['name'] as $i => $name) {

    $name = $_FILES['files']['name'][$i];
    $size = $_FILES['files']['size'][$i];
    $type = $_FILES['files']['type'][$i];
    $tmp = $_FILES['files']['tmp_name'][$i];

    $explode = explode('.', $name);

    $ext = end($explode);

    $updatdName = $explode[0] . time() .'.'. $ext;
    $path = 'uploads/';
    $path = $path . basename( $updatdName );

    if(empty($_FILES['files']['tmp_name'][$i])) {
        $errors[] = 'Please choose at least 1 file to be uploaded.';
    }else {

        $allowed = array('jpg','jpeg','gif','bmp','png');

        $max_size = 2000000; // 2MB

        if(in_array($ext, $allowed) === false) {
            $errors[] = 'The file <b>'.$name.'</b> extension is not allowed.';
        }

        if($size > $max_size) {
            $errors[] = 'The file <b>'.$name.'</b> size is too hight.';
        }

    }

    if(empty($errors)) {

        // if there is no error then set values
        $files['file_name'][] = $updatdName;
        $files['size'][] = $size;
        $files['type'][] = $type;
        $errors = array();
        if(!file_exists('uploads')) {
            mkdir('uploads', 0777);
        }

        if(move_uploaded_file($tmp, $path)) {
            echo '<p>The file <b>'.$name.'</b> successful upload</p>';
        }else {
            echo 'Something went wrong while uploading
     <b>'.$name.'</b>';
        }

    }else {
        foreach($errors as $error) {
            echo '<p>'.$error.'<p>';
        }
    }

}

if(!empty($files)) {

    $files['file_name'][] = $updatdName;
    $files['size'][] = $size;
    $files['type'][] = $type;
    $names = implode(',', $files['file_name']);
    $sizes = implode(',', $files['size']);
    $types = implode(',', $files['type']);
    $sql="INSERT into pictures (FILE_NAME, FILE_SIZE, FILE_TYPE )
         VALUES('$names','$sizes','$types'); ";
    mysqli_query($conn, $sql);
}

I think this will help you.


问:
library manage account with asp.net
I have trouble creating a project with asp .net. and terelik
I have to create a system. Account management Everytime i want to know Which libraries help to create account management with .net and support the terelik ui
some thing like manage rule for the any method, just install packages then the packages has initial the table model controller or something.</p>

答:
I guess there are no package which you can just install and get everything already done but there are number of projects in code project site. You can download them and integrate. Beside that you can use Microsoft Identity which provide bootstrap code for user registration/login and you can customize according to your need and role base access can be simply done in mvc just by providing role in controller attribute.

And I am not aware of Telerik providing such functionality. You should implement those using Telerik controls.

Title: library manage account with asp.net


问:
code before app.run() can not be run in gunicorn+flask
```<code>#main.py
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    print("before app run")
    app.run()  # , threaded=True host='0.0.0.0', debug=True, port=5000
</code>```

Run gunicorn as follow:

```<code>gunicorn -b 0.0.0.0:8000 --preload main:app
</code>```

the result will not print “before app unn”. How can i run the print code? if i don't want to place print outside of if __name__ == '__main__'

答:
Actually that will print before app run when you run this application with python main.py

It's not possible with Gunicorn though you can try before_first_request that will do the trick

```<code>@app.before_first_request
def execute_this():
    print("before app run")
</code>```

Body:
#main.py
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
    print("before app run")
    app.run()  # , threaded=True host='0.0.0.0', debug=True, port=5000

Run gunicorn as follow:

gunicorn -b 0.0.0.0:8000 --preload main:app

the result will not print “before app unn”. How can i run the print code? if i don't want to place print outside of if __name__ == '__main__'

Body:
Actually that will print before app run when you run this application with python main.py

It's not possible with Gunicorn though you can try before_first_request that will do the trick

@app.before_first_request
def execute_this():
    print("before app run")


问:
hasAuthority method for only POST and PUT httpmethods
Here is my configure code snippet

```<code>@Override
    public void configure(HttpSecurity http) throws Exception {
        http.
        authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/api/user/**").hasAnyAuthority("ROLE_ADMIN")
        .antMatchers("/api/status/**").hasAuthority("ROLE_ADMIN").anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .accessDeniedHandler(new OAuth2AccessDeniedHandler());
        }
</code>```

In this I need to make ROLE_ADMIN to access only POST and PUT httpmethods. He should not be able to access GET or DELETE httpmethod. I need this to be done in a single .antMatchers() method.
How can I do this?

答:
Have a look at this Spring example project. You can define matchers per path and HTTP verb.

http
    .authorizeRequests()
        .antMatchers(HttpMethod.POST, "/employees").hasRole("ADMIN")
        .antMatchers(HttpMethod.PUT, "/employees/**").hasRole("ADMIN")
        .antMatchers(HttpMethod.PATCH, "/employees/**").hasRole("ADMIN")
```

Body:
Here is my configure code snippet

@Override
    public void configure(HttpSecurity http) throws Exception {
        http.
        authorizeRequests()
        .antMatchers("/").permitAll()
        .antMatchers("/api/user/**").hasAnyAuthority("ROLE_ADMIN")
        .antMatchers("/api/status/**").hasAuthority("ROLE_ADMIN").anyRequest()
        .authenticated()
        .and()
        .exceptionHandling()
        .accessDeniedHandler(new OAuth2AccessDeniedHandler());
        }

In this I need to make ROLE_ADMIN to access only POST and PUT httpmethods. He should not be able to access GET or DELETE httpmethod. I need this to be done in a single .antMatchers() method.
How can I do this?


问:
AngularFire2 OAuth2 with Google getting Firebase Authorization error
I am trying to use Google Authentication to get written permission to my Firebase data.  However, while I believe I have most things configured, it is not working when I attempt to connect to Google, and I am not sure what to set next.

Login function on my page:

```<code>import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
...
constructor(public navCtrl: NavController, public navParams: NavParams, public AFAuth: AngularFireAuth) { }
...
login() {

    this.AFAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider())
        .then(function(result) {
            this.GoogleAccessToken = result.credential.accessToken;     // This gives you a Google Access Token. You can use it to access the Google API.
            this.GoogleUser = result.user;                          // The signed-in user info.
            this.LoggedIn = true;
            console.log('Logged In');
        })
        .catch(function(error) {
            console.log('Error Logging In: ' + error)
        }
    );
}
</code>```

I am always getting this error:

```<code>Error Logging In: Error: This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.
</code>```

Note the my data is set to Read only, and my application accesses all the data correctly, so I have the AngularFire Firebase connection strings correct.

I have also validated that the Firebase.apiKey and Firebase.authDomain both match the settings in the Google API Manager.  My authDomain is also white listed on the Browser key (auto created by Google Service) as an HTTP referrers (web sites).

I have tried this from my localhost with port being whitelisted (development machine) and by placing the code on the website to test it, and it also fails.

All the references are http://xxxxx.domain.com, without the www as we do not access our application from www.domain.com.

To remove the reference settings as a possible issue, I have changed the reference filter to None.  However, this then results in an Error 401, deleted_client.  The OAth client was deleted.

答:
You must have some referrer restrictions on your browser API key.
In the Google Cloud Console, go to the browser key that you are using, typically it is labeled (auto created by Google service) and set "Key restriction" to "None".</p>

Body:
I am trying to use Google Authentication to get written permission to my Firebase data.  However, while I believe I have most things configured, it is not working when I attempt to connect to Google, and I am not sure what to set next.

Login function on my page:

import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from 'firebase/app';
...
constructor(public navCtrl: NavController, public navParams: NavParams, public AFAuth: AngularFireAuth) { }
...
login() {

    this.AFAuth.auth.signInWithRedirect(new firebase.auth.GoogleAuthProvider())
        .then(function(result) {
            this.GoogleAccessToken = result.credential.accessToken;     // This gives you a Google Access Token. You can use it to access the Google API.
            this.GoogleUser = result.user;                          // The signed-in user info.
            this.LoggedIn = true;
            console.log('Logged In');
        })
        .catch(function(error) {
            console.log('Error Logging In: ' + error)
        }
    );
}

I am always getting this error:

Error Logging In: Error: This app, identified by the domain where it's hosted, is not authorized to use Firebase Authentication with the provided API key. Review your key configuration in the Google API console.

Note the my data is set to Read only, and my application accesses all the data correctly, so I have the AngularFire Firebase connection strings correct.

I have also validated that the Firebase.apiKey and Firebase.authDomain both match the settings in the Google API Manager.  My authDomain is also white listed on the Browser key (auto created by Google Service) as an HTTP referrers (web sites).

I have tried this from my localhost with port being whitelisted (development machine) and by placing the code on the website to test it, and it also fails.

All the references are http://xxxxx.domain.com, without the www as we do not access our application from www.domain.com.

To remove the reference settings as a possible issue, I have changed the reference filter to None.  However, this then results in an Error 401, deleted_client.  The OAth client was deleted.


问:
What is a convenient way to upgrade dependencies across multiple npm projects?
For open-source library authors, especially React-related, it is common for them to have written and published multiple React components. However, when React releases a new version (e.g v16), it is a hassle to upgrade each of those components to the latest React version.

What's a convenient way to upgrade the React dependencies in all those packages, with stability in mind? I don't want to be manually going into each project and running npm update as that will take very long. I considered writing a script to do it for me, but I'm wondering if there is any tool out there they can do the same or even better, and upgrade packages in all my projects at once?

This question is not really specific to React, it can apply to Angular, Vue, etc, or other commonly used npm library as well.

答:
Simplest way to update dependencies:

```<code>npm update
</code>```

It will update only on based ranges in package.json, eg. from 1.0.0 to 1.9.0, but not to 2.0.0. See semantic versioning. It's not good idea to setup automatic major version upgrade in package.json, so usually npm update will ignore major releases.

If you want to upgrade dependencies major versions, it's more trickier. There is high possibility that there will be breaking changes in libs, and you would need to upgrade your code as well.

What can help you with update to latest versions is this library npm-check-updates.

```<code> npm install -g npm-check-updates
 ncu // Shows new dependencies
 ncu -u // Will do upgrade in package.json
</code>```

This library will search for latest packages and even will do update.

Specifically for React there is CLI which may be used, if you don't need custom webpack build. React-create-app will create application with hidden dependencies like React, ReactDOM, Jest, Webpack, .. and when you want to upgrade then it's as simple as updating one dependency for whole React&Webpack stack.

```<code>npm install -g create-react-app
create-react-app my-app
cd my-app/
npm start
</code>```

If you are building similar applications (but cannot use ReactCLI), you can build your own webpack configuration which might be reused in all your application and it will cover build process. This might hide build dependencies like Webpack, React, Router, etc.

Update: Is possible to upgrade multiple projects quickly and seamlessly? eg. with simple script.

It's probably very complicated or even impossible. You would need to have exactly same dependencies in all projects... as you might have some incompatible versions of different libs. Probably best way would be to create common libraries stack like react-cli has and then use this stack as single dependency. But still you would need to upgrade and test each project separately after upgrade of "stack" dependency - also usually you would also need to upgrade codebase because of API changes. Making update script may be quite complex and probably not worth it.

Body:
Simplest way to update dependencies:

npm update

It will update only on based ranges in package.json, eg. from 1.0.0 to 1.9.0, but not to 2.0.0. See semantic versioning. It's not good idea to setup automatic major version upgrade in package.json, so usually npm update will ignore major releases.

If you want to upgrade dependencies major versions, it's more trickier. There is high possibility that there will be breaking changes in libs, and you would need to upgrade your code as well.

What can help you with update to latest versions is this library npm-check-updates.

 npm install -g npm-check-updates
 ncu // Shows new dependencies
 ncu -u // Will do upgrade in package.json

This library will search for latest packages and even will do update.

Specifically for React there is CLI which may be used, if you don't need custom webpack build. React-create-app will create application with hidden dependencies like React, ReactDOM, Jest, Webpack, .. and when you want to upgrade then it's as simple as updating one dependency for whole React&Webpack stack.

npm install -g create-react-app
create-react-app my-app
cd my-app/
npm start

If you are building similar applications (but cannot use ReactCLI), you can build your own webpack configuration which might be reused in all your application and it will cover build process. This might hide build dependencies like Webpack, React, Router, etc.

Update: Is possible to upgrade multiple projects quickly and seamlessly? eg. with simple script.

It's probably very complicated or even impossible. You would need to have exactly same dependencies in all projects... as you might have some incompatible versions of different libs. Probably best way would be to create common libraries stack like react-cli has and then use this stack as single dependency. But still you would need to upgrade and test each project separately after upgrade of "stack" dependency - also usually you would also need to upgrade codebase because of API changes. Making update script may be quite complex and probably not worth it.


问:
how to check the Jboss (EAP 7) server running status via shell script
I have multiple jboss instance on a particular linux box . I don't want to grep the process id of jboss instance and listen port .Is there any work around from server.log or CLI command ?</p>

答:
In addition to the Panagiotis Chavarioti´s answer, the status of the application component also can be checked with the commands which are handy.

To check if JBoss server is started:

```<code>$JBOSS_HOME/bin/jboss-cli.sh -c --commands="read-attribute server-state"
</code>```

To check if application is started:

```<code>$JBOSS_HOME/bin/jboss-cli.sh -c --commands="cd deployment,cd myapp.war, read-attribute status"
</code>```

example:

```<code>$JBOSS_HOME/bin/jboss-cli.sh -c
'/host=sandbox/server=server1:readattribute(name=server-state)'
</code>```

Body:
In addition to the Panagiotis Chavarioti´s answer, the status of the application component also can be checked with the commands which are handy.

To check if JBoss server is started:

$JBOSS_HOME/bin/jboss-cli.sh -c --commands="read-attribute server-state"

To check if application is started:

$JBOSS_HOME/bin/jboss-cli.sh -c --commands="cd deployment,cd myapp.war, read-attribute status"

example:

$JBOSS_HOME/bin/jboss-cli.sh -c
'/host=sandbox/server=server1:readattribute(name=server-state)'


问:
Cursors with LOOP
Sorry for the huge code. All I am trying to do is increment the variable YM1 (201702, 201703, 201704) by one month, execute the SQL statement and display the result using CURSOR.

CURRENT BEHAVIOR: The YM1 variable is not incremented. The code executes but always uses YM1 = '201702'.

```<code>YEAR_MONTH 201701 201702 0
YEAR_MONTH 201701 201703 0
YEAR_MONTH 201701 201704 0
</code>```

EXPECTED RESULT:

```<code>YEAR_MONTH 201701 201702 0
YEAR_MONTH 201701 201703 10
YEAR_MONTH 201701 201704 20
</code>```

Please let me know what I am missing. Breaking my head. Thanks a lot for the time.

```<code>set serveroutput on

DECLARE
    YM   VARCHAR2(10) := '201701';
    YM1  VARCHAR2(10) := '201702';
    row1 number := 0;

    CURSOR counts is
        SELECT COUNT(*)
        FROM   **table1 a**
        WHERE  a.year_month = YM
        AND    EXISTS
               ( SELECT 'Y'
                 FROM   **table2 b**
                 WHERE  a.id = b.id
                 AND    b.year_month = YM1 );
BEGIN
    OPEN counts;
    LOOP
        FETCH counts INTO row1;
        dbms_output.put_line('YEAR_MONTH '||YM||' '||YM1||' '||row1);
        YM1 := TO_CHAR(ADD_MONTHS(TO_DATE(YM1,'YYYY-MM'), +1), 'YYYYMM');
        EXIT WHEN YM1 > '201704'
    END LOOP;
    CLOSE counts;
END;
/
</code>```

答:
The problem is, when you open the cursor it selects all the records that match the YM1 variable at the time of opening. So your loop will fetch one row which  exhausts the cursor. The next fetch fetches nothing and so the value of row1 is not updated.

To pick up fresh values you need to open and close the cursor each time:

```<code>DECLARE
  YM VARCHAR2(10) := '201701'
  YM1 VARCHAR2(10) := '201702'
  row1 number := 0;
  CURSOR counts is
     SELECT COUNT(*)
     FROM table1 a
     WHERE a.YEAR_MONTH = YM
     AND EXISTS (SELECT 'Y'
                 FROM table2 b
                 WHERE a.id = b.id
                 AND b.YEAR_MONTH  = YM1);
BEGIN
  LOOP
    OPEN counts;
    FETCH counts INTO row1;
    dbms_output.put_line('YEAR_MONTH '||YM||' '||YM1||' '||row1);
    YM1 := TO_CHAR(ADD_MONTHS(TO_DATE(YM1,'YYYY-MM'), +1), 'YYYYMM');
    EXIT WHEN YM1 > '201704'
    CLOSE counts;
  END LOOP;
END;
/
</code>```

Title: Cursors with LOOP

Body:
Sorry for the huge code. All I am trying to do is increment the variable YM1 (201702, 201703, 201704) by one month, execute the SQL statement and display the result using CURSOR.

CURRENT BEHAVIOR: The YM1 variable is not incremented. The code executes but always uses YM1 = '201702'.

YEAR_MONTH 201701 201702 0
YEAR_MONTH 201701 201703 0
YEAR_MONTH 201701 201704 0

EXPECTED RESULT:

YEAR_MONTH 201701 201702 0
YEAR_MONTH 201701 201703 10
YEAR_MONTH 201701 201704 20

Please let me know what I am missing. Breaking my head. Thanks a lot for the time.

set serveroutput on

DECLARE
    YM   VARCHAR2(10) := '201701';
    YM1  VARCHAR2(10) := '201702';
    row1 number := 0;

    CURSOR counts is
        SELECT COUNT(*)
        FROM   **table1 a**
        WHERE  a.year_month = YM
        AND    EXISTS
               ( SELECT 'Y'
                 FROM   **table2 b**
                 WHERE  a.id = b.id
                 AND    b.year_month = YM1 );
BEGIN
    OPEN counts;
    LOOP
        FETCH counts INTO row1;
        dbms_output.put_line('YEAR_MONTH '||YM||' '||YM1||' '||row1);
        YM1 := TO_CHAR(ADD_MONTHS(TO_DATE(YM1,'YYYY-MM'), +1), 'YYYYMM');
        EXIT WHEN YM1 > '201704'
    END LOOP;
    CLOSE counts;
END;
/

Body:
The problem is, when you open the cursor it selects all the records that match the YM1 variable at the time of opening. So your loop will fetch one row which  exhausts the cursor. The next fetch fetches nothing and so the value of row1 is not updated.

To pick up fresh values you need to open and close the cursor each time:

DECLARE
  YM VARCHAR2(10) := '201701'
  YM1 VARCHAR2(10) := '201702'
  row1 number := 0;
  CURSOR counts is
     SELECT COUNT(*)
     FROM table1 a
     WHERE a.YEAR_MONTH = YM
     AND EXISTS (SELECT 'Y'
                 FROM table2 b
                 WHERE a.id = b.id
                 AND b.YEAR_MONTH  = YM1);
BEGIN
  LOOP
    OPEN counts;
    FETCH counts INTO row1;
    dbms_output.put_line('YEAR_MONTH '||YM||' '||YM1||' '||row1);
    YM1 := TO_CHAR(ADD_MONTHS(TO_DATE(YM1,'YYYY-MM'), +1), 'YYYYMM');
    EXIT WHEN YM1 > '201704'
    CLOSE counts;
  END LOOP;
END;
/


问:
Javascript Regular Expression For a Valid Input
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).<br>
e.g   </p>

```<code>12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid
</code>```

Body:
I want JavaScript regular expression which validates below number format (only number and min length should be 11 and maximum 16).

e.g

12345678901 // valid
+1234567890 // valid
+1234567890+ // invalid
+123456789trtr // invalid
+trtr // invalid

Body:
try this regex:

/([+]?[0-9]{1,10})\w+/g


问:
How to use increment method for findElement code
I'm stuck with how to implicate increment into find element code

this is the code

```<code>driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[13]")).click();
</code>```

I need to change 13 into 13 + 1 and 14 + 1 and so on every time loop happens.

答:
Use variable</p>

```<code>for (int i = 13 ; i < limit ; ++i) {
    driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[" + i + "]")).click();
}
</code>```

Body:
I'm stuck with how to implicate increment into find element code

this is the code

driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[13]")).click();

I need to change 13 into 13 + 1 and 14 + 1 and so on every time loop happens.

Body:
Use variable

for (int i = 13 ; i < limit ; ++i) {
    driver.findElement(By.xpath("(//a[@class='_8mlbc _vbtk2 _t5r8b'])[" + i + "]")).click();
}


问:
How to use dataset to groupby
I have a request to use rdd to do so：

```<code>val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)
</code>```

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

答:
I would suggest you to start with creating a case class as

```<code>case class Monkey(city: String, firstName: String)
</code>```

This case class should be defined outside the main class. Then you can just use toDS function and use groupBy and aggregation function called collect_list as below

```<code>import sqlContext.implicits._
import org.apache.spark.sql.functions._

val test = Seq(("New York", "Jack"),
  ("Los Angeles", "Tom"),
  ("Chicago", "David"),
  ("Houston", "John"),
  ("Detroit", "Michael"),
  ("Chicago", "Andrew"),
  ("Detroit", "Peter"),
  ("Detroit", "George")
)
sc.parallelize(test)
  .map(row => Monkey(row._1, row._2))
  .toDS()
  .groupBy("city")
  .agg(collect_list("firstName") as "list")
  .show(false)
</code>```

You will have output as

```<code>+-----------+------------------------+
|city       |list                    |
+-----------+------------------------+
|Los Angeles|[Tom]                   |
|Detroit    |[Michael, Peter, George]|
|Chicago    |[David, Andrew]         |
|Houston    |[John]                  |
|New York   |[Jack]                  |
+-----------+------------------------+
</code>```

You can always convert back to RDD by just calling .rdd function

Title: How to use dataset to groupby

Body:
I have a request to use rdd to do so：

val test = Seq(("New York", "Jack"),
    ("Los Angeles", "Tom"),
    ("Chicago", "David"),
    ("Houston", "John"),
    ("Detroit", "Michael"),
    ("Chicago", "Andrew"),
    ("Detroit", "Peter"),
    ("Detroit", "George")
  )
sc.parallelize(test).groupByKey().mapValues(_.toList).foreach(println)

The result is that：

(New York,List(Jack))

(Detroit,List(Michael, Peter, George))

(Los Angeles,List(Tom))

(Houston,List(John))

(Chicago,List(David, Andrew))

How to do it use dataset with spark2.0?

I have a way to use a custom function, but the feeling is so complicated, there is no simple point method？

Body:
I would suggest you to start with creating a case class as

case class Monkey(city: String, firstName: String)

This case class should be defined outside the main class. Then you can just use toDS function and use groupBy and aggregation function called collect_list as below

import sqlContext.implicits._
import org.apache.spark.sql.functions._

val test = Seq(("New York", "Jack"),
  ("Los Angeles", "Tom"),
  ("Chicago", "David"),
  ("Houston", "John"),
  ("Detroit", "Michael"),
  ("Chicago", "Andrew"),
  ("Detroit", "Peter"),
  ("Detroit", "George")
)
sc.parallelize(test)
  .map(row => Monkey(row._1, row._2))
  .toDS()
  .groupBy("city")
  .agg(collect_list("firstName") as "list")
  .show(false)

You will have output as

+-----------+------------------------+
|city       |list                    |
+-----------+------------------------+
|Los Angeles|[Tom]                   |
|Detroit    |[Michael, Peter, George]|
|Chicago    |[David, Andrew]         |
|Houston    |[John]                  |
|New York   |[Jack]                  |
+-----------+------------------------+

You can always convert back to RDD by just calling .rdd function

ContentLicense: CC BY-SA 4.0


问:
Are references orthogonal to pointers?
The question is meant as language orthogonal(as is in lack of redundency) features. References (never null[1]) in C++ can be implemented with pointers while compilers check for the semantic differences. There are languages like Java or C# that only have references (maybe null) but no pointers and C has it the other way round. So one is sufficent for a complete language. Is the behaviour in C++ different enough to be orthogonal?

[1] You can de-reference a nullptr but that is undefined.

答:
Here is a difference between pointers and references to consider.

```<code>#include <vector>

int main() {
   // Compiles and it contains pointers to ints
   std::vector<int*> vpInts;
   return 0;
}
</code>```

Versus

```<code>#include <vector>

int main() {
    // Does not compile
    std::vector<int&> vrInts;
    return 0;
}
</code>```

The second case is illegal this is especially shown in MSVS's compiler error from MSVS2017 CE.

```<code>1>------ Build started: Project: Test1z, Configuration: Debug Win32 ------
1>main.cpp
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(774): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(984): note: see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(441): note: see reference to class template instantiation 'std::_Wrap_alloc<std::allocator<_Ty>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(493): note: see reference to class template instantiation 'std::_Vec_base_types<_Ty,_Alloc>' being compiled
1>        with
1>        [
1>            _Ty=int &,
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(701): note: see reference to class template instantiation 'std::_Vector_alloc<std::_Vec_base_types<_Ty,_Alloc>>' being compiled
1>        with
1>        [
1>            _Ty=int &,
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\users\skilz80\documents\visual studio 2017\projects\test1z\test1z\main.cpp(15): note: see reference to class template instantiation 'std::vector<int &,std::allocator<_Ty>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(775): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(798): error C2535: 'int &(*std::allocator<_Ty>::address(int &) noexcept const)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(792): note: see declaration of 'std::allocator<_Ty>::address'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(918): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(988): note: see reference to class template instantiation 'std::allocator_traits<_Alloc>' being compiled
1>        with
1>        [
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(919): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(938): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(944): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(1031): error C2535: 'int &(*std::_Wrap_alloc<std::allocator<_Ty>>::address(int &) const)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(1025): note: see declaration of 'std::_Wrap_alloc<std::allocator<_Ty>>::address'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(159): error C2528: 'abstract declarator': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(444): note: see reference to class template instantiation 'std::_Is_simple_alloc<std::_Wrap_alloc<std::allocator<_Ty>>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(159): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(161): error C2528: 'abstract declarator': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(161): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(452): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(176): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(497): note: see reference to class template instantiation 'std::_Simple_types<int &>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(177): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(951): error C2535: 'void std::vector<int &,std::allocator<_Ty>>::push_back(_Ty)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(945): note: see declaration of 'std::vector<int &,std::allocator<_Ty>>::push_back'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1033): error C2535: 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int &>>> std::vector<int &,std::allocator<_Ty>>::insert(std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<int &>>>,_Ty)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1027): note: see declaration of 'std::vector<int &,std::allocator<_Ty>>::insert'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1634): error C2528: 'data': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1639): error C2528: 'data': pointer to reference is illegal
1>Done building project "Test1z.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
</code>```

Basically in C++  a pointer itself is a declared variable that takes up memory either on the stack or the heap  where a reference may or may not for it references an already created object or variable that is already in memory. It depends on how the compiler will treat it; some compilers will optimize the memory footprint away by using move semantics by pushing and popping value in and out of registers while a pointer variable will always take up a specified amount of memory. There are similarities such that a pointer does point to the memory address of another variable or object and that a reference references the memory address of an already created instance of another variable or object.

Title: Are references orthogonal to pointers?

Body:
Here is a difference between pointers and references to consider.

#include <vector>

int main() {
   // Compiles and it contains pointers to ints
   std::vector<int*> vpInts;
   return 0;
}

Versus

#include <vector>

int main() {
    // Does not compile
    std::vector<int&> vrInts;
    return 0;
}

The second case is illegal this is especially shown in MSVS's compiler error from MSVS2017 CE.

1>------ Build started: Project: Test1z, Configuration: Debug Win32 ------
1>main.cpp
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(774): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(984): note: see reference to class template instantiation 'std::allocator<_Ty>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(441): note: see reference to class template instantiation 'std::_Wrap_alloc<std::allocator<_Ty>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(493): note: see reference to class template instantiation 'std::_Vec_base_types<_Ty,_Alloc>' being compiled
1>        with
1>        [
1>            _Ty=int &,
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(701): note: see reference to class template instantiation 'std::_Vector_alloc<std::_Vec_base_types<_Ty,_Alloc>>' being compiled
1>        with
1>        [
1>            _Ty=int &,
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\users\skilz80\documents\visual studio 2017\projects\test1z\test1z\main.cpp(15): note: see reference to class template instantiation 'std::vector<int &,std::allocator<_Ty>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(775): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(798): error C2535: 'int &(*std::allocator<_Ty>::address(int &) noexcept const)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(792): note: see declaration of 'std::allocator<_Ty>::address'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(918): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(988): note: see reference to class template instantiation 'std::allocator_traits<_Alloc>' being compiled
1>        with
1>        [
1>            _Alloc=std::allocator<int &>
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(919): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(938): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(944): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(1031): error C2535: 'int &(*std::_Wrap_alloc<std::allocator<_Ty>>::address(int &) const)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(1025): note: see declaration of 'std::_Wrap_alloc<std::allocator<_Ty>>::address'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(159): error C2528: 'abstract declarator': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(444): note: see reference to class template instantiation 'std::_Is_simple_alloc<std::_Wrap_alloc<std::allocator<_Ty>>>' being compiled
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(159): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(161): error C2528: 'abstract declarator': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(161): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(452): error C2528: '<template-parameter>': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(176): error C2528: 'pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(497): note: see reference to class template instantiation 'std::_Simple_types<int &>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\xmemory0(177): error C2528: 'const_pointer': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(951): error C2535: 'void std::vector<int &,std::allocator<_Ty>>::push_back(_Ty)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(945): note: see declaration of 'std::vector<int &,std::allocator<_Ty>>::push_back'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1033): error C2535: 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int &>>> std::vector<int &,std::allocator<_Ty>>::insert(std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<int &>>>,_Ty)': member function already defined or declared
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1027): note: see declaration of 'std::vector<int &,std::allocator<_Ty>>::insert'
1>        with
1>        [
1>            _Ty=int &
1>        ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1634): error C2528: 'data': pointer to reference is illegal
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.10.25017\include\vector(1639): error C2528: 'data': pointer to reference is illegal
1>Done building project "Test1z.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Basically in C++  a pointer itself is a declared variable that takes up memory either on the stack or the heap  where a reference may or may not for it references an already created object or variable that is already in memory. It depends on how the compiler will treat it; some compilers will optimize the memory footprint away by using move semantics by pushing and popping value in and out of registers while a pointer variable will always take up a specified amount of memory. There are similarities such that a pointer does point to the memory address of another variable or object and that a reference references the memory address of an already created instance of another variable or object.


问:
Need some help for X pages Set Authenticate access
i have created a webpage using xpages. I not sure how to use Access control rules to force user to go login page and check for "address book" account.

Below will be the sample page i created using xpages.

Submit button to check address book whether this person is exist or not

Anonymous to request for an email address for their address book. This one will by pass the validation and go to the request page but only "Anonymous can access".

Login...Go to "Approved page", but before that, user need to go to server login screen to login his user account.

答:
You lock down the database to enforce the authentication access:

Edit the ACL (File - Application - Access Control) and set access for Anonymous to "No Access" but check "Read Public Documents"

Now you would need to authenticate for every page (which is not what you want), so you edit xpage properties and check "Available for public access Users" property for all pages a user shall be able to access unauthenticated

You might need to flag a few additional design elements too (check the official details)

While you are on it: customise your login page in domcfg.nsf

More on ACL basics: https://www.wissel.net/blog/2010/09/access-control-in-domino-the-basics.html

If your struggle, give me a call (the NRIC in the screenshot suggest you are in Singapore like me)


问:
Seed performance and reliability from urandom
```<code>#!/bin/bash

seed1=0
seed2=0

while [[ "$seed1" == 0 || "$seed2" == 0 ]]; do
    seed1=$(head -c 4096 /dev/urandom | tr -dc '0-9' | fold -w 16 | head -n 1)
    seed2=$(head -c 4096 /dev/urandom | tr -dc '0-9' | fold -w 16 | head -n 1)
done

seed_array=($seed1 $seed2)
seed_array=($(echo ${seed_array[*]}| tr " " "\n" | sort -n))

salt_num=[some function id rather not reveal] < /dev/urandom
echo $(echo [seed and salt go here in some order id rather not say] | sha256sum | awk '{print $1}')
</code>```

I'm creating a seed and a salt for something or other I'm trying to put together, here's a dirty version. now, I like the way this is starting to work, because I'm getting a lot of really good randomness here. But I need to strive for the highest entropy here. I think urandom is the tool for the job, but I don't know how i feel about tr -dc '0-9' right after I pull 4k items from it. it makes it so i have to fold 16 instead of 32, which is what I would prefer. because sometimes, there just aren't enough numbers to choose from.

to be clear, i would like to achieve the following constraints:

head -c 4096 as maximum pull from urandom during any one command

seed1, seed2 should be a series of 32 ints 0-9 as random as possible

if possible, would like to increase fold to 32 reliably (there can never be a seed below a character count of 32)

pulling less from urandom is fine. if entropy is preserved.

other suggestions are ok if and only if entropy is increased

Like I said before, the tr -dc '0-9' just feels sloppy. and if possible, is there a way to increase the amount of bytes I use from urandom (currently just basically filtering anything that isn't an int already).

it works, but i feel like there must be a better way. anyone with a fresh pair of eyes see something I'm missing?

答: what about adding | od -An -tx8 between head and tr to convert output in hex so that 0-9 have more likely to occur.

Body:
#!/bin/bash

seed1=0
seed2=0

while [[ "$seed1" == 0 || "$seed2" == 0 ]]; do
    seed1=$(head -c 4096 /dev/urandom | tr -dc '0-9' | fold -w 16 | head -n 1)
    seed2=$(head -c 4096 /dev/urandom | tr -dc '0-9' | fold -w 16 | head -n 1)
done

seed_array=($seed1 $seed2)
seed_array=($(echo ${seed_array[*]}| tr " " "\n" | sort -n))

salt_num=[some function id rather not reveal] < /dev/urandom
echo $(echo [seed and salt go here in some order id rather not say] | sha256sum | awk '{print $1}')

I'm creating a seed and a salt for something or other I'm trying to put together, here's a dirty version. now, I like the way this is starting to work, because I'm getting a lot of really good randomness here. But I need to strive for the highest entropy here. I think urandom is the tool for the job, but I don't know how i feel about tr -dc '0-9' right after I pull 4k items from it. it makes it so i have to fold 16 instead of 32, which is what I would prefer. because sometimes, there just aren't enough numbers to choose from.

to be clear, i would like to achieve the following constraints:

head -c 4096 as maximum pull from urandom during any one command

seed1, seed2 should be a series of 32 ints 0-9 as random as possible

if possible, would like to increase fold to 32 reliably (there can never be a seed below a character count of 32)

pulling less from urandom is fine. if entropy is preserved.

other suggestions are ok if and only if entropy is increased

Like I said before, the tr -dc '0-9' just feels sloppy. and if possible, is there a way to increase the amount of bytes I use from urandom (currently just basically filtering anything that isn't an int already).

it works, but i feel like there must be a better way. anyone with a fresh pair of eyes see something I'm missing?


问:
clang + libc++: combination of make_tuple with make_shared leads to early object destruction
I've lost almost all day tracking bug in my program. For some reason, my implementation of std::apply in terms of c++11 was faulty: arguments to the underlying function somehow got empty in the middle of call. Good example is std::unique_ptr that after call to a makeshift function (below, foo()) was always empty() in the body of called function.

I've dumbed down my code to a simple test case:

```<code>#include <tuple>
#include <memory>
#include <iostream>

struct Foo
{
    Foo()
    {
        std::cout << "Foo()" << std::endl;
    }

    ~Foo()
    {
        std::cout << "~Foo()" << std::endl;
    }
};

template <typename ...Args>
void foo(Args && ...args)
{
    using TupleType = decltype(std::make_tuple(std::forward<Args>(args)...));

    std::cout << "Point #1" << std::endl;

    /// Package arguments to a function.
    auto && packaged_args = std::make_shared<TupleType>(std::make_tuple(std::forward<Args>(args)...));

    std::cout << "Point #2" << std::endl;
}

int main()
{
    std::unique_ptr<Foo> foo_var{new Foo};

    foo(std::move(foo_var));
    return 0;
}
</code>```

If compiled with clang together with libc++ (-stdlib=libc++) the results are:

```<code>Foo()
Point #1
~Foo()
Point #2
</code>```

Live example on coliru.stacked-crooked.com

The results are obviously incorrect. If compiled with clang, but without libc++, or if compiled with gcc, the results are as expected:

```<code>Foo()
Point #1
Point #2
~Foo()
</code>```

I found a laughable workaround for the combination of clang and libc++, replace:

```<code>auto && packaged_args = std::make_shared<TupleType>(std::make_tuple(std::forward<Args>(args)...));
</code>```

with:

```<code>std::shared_ptr<TupleType> packaged_args{new TupleType(std::make_tuple(std::forward<Args>(args)...))};
</code>```

and it again works as expected.

Live example on coliru.stacked-crooked.com

The qustion is: is it an UB, so that both compilers are right with the wrong code or the code is okay and this is a bug?

答:
This seems to be a bug in libc++'s tuple implementation.

The bug exists in Libc++ <= 3.8, but has been fixed by my tuple rewrite in 3.9.

Sorry about the bug; it appears the best/only way to avoid it is upgrade.

Body:
I've lost almost all day tracking bug in my program. For some reason, my implementation of std::apply in terms of c++11 was faulty: arguments to the underlying function somehow got empty in the middle of call. Good example is std::unique_ptr that after call to a makeshift function (below, foo()) was always empty() in the body of called function.

I've dumbed down my code to a simple test case:

#include <tuple>
#include <memory>
#include <iostream>

struct Foo
{
    Foo()
    {
        std::cout << "Foo()" << std::endl;
    }

    ~Foo()
    {
        std::cout << "~Foo()" << std::endl;
    }
};

template <typename ...Args>
void foo(Args && ...args)
{
    using TupleType = decltype(std::make_tuple(std::forward<Args>(args)...));

    std::cout << "Point #1" << std::endl;

    /// Package arguments to a function.
    auto && packaged_args = std::make_shared<TupleType>(std::make_tuple(std::forward<Args>(args)...));

    std::cout << "Point #2" << std::endl;
}

int main()
{
    std::unique_ptr<Foo> foo_var{new Foo};

    foo(std::move(foo_var));
    return 0;
}

If compiled with clang together with libc++ (-stdlib=libc++) the results are:

Foo()
Point #1
~Foo()
Point #2

Live example on coliru.stacked-crooked.com

The results are obviously incorrect. If compiled with clang, but without libc++, or if compiled with gcc, the results are as expected:

Foo()
Point #1
Point #2
~Foo()

I found a laughable workaround for the combination of clang and libc++, replace:

auto && packaged_args = std::make_shared<TupleType>(std::make_tuple(std::forward<Args>(args)...));

with:

std::shared_ptr<TupleType> packaged_args{new TupleType(std::make_tuple(std::forward<Args>(args)...))};

and it again works as expected.

Live example on coliru.stacked-crooked.com

The qustion is: is it an UB, so that both compilers are right with the wrong code or the code is okay and this is a bug?


问:
SSIS - Determine which tasks failed, send single email with details
I've got a simple package which updates my database then exports data to five different files. What I'm trying to do is produce an email which details whether each of the exports have run successfully. So I want something like this in the email:

```<code>|EXPORT | STATUS  |
| 4     | Success |
| 5     | Success |
| 6     | Success |
| 7     | Failed  |
| 8     | Success |
</code>```

Initially, I had separate Success and Fail (Logical OR) email tasks set up. This allowed me to determine that either all the tasks succeeded or at least one failed... but that wasn't what I wanted.

Then, I looked at this example and rewriting it in C# within my script task, but I realised that the variables in the example didn't seem to exist (script would throw an error), so I tried creating user variables and passing them through in the ReadWriteVariables, the script would run successfully but nothing would be displayed in the Send Mail Task, the the script wasn't actually doing anything.

I've looked at a few similar questions and this one seems to be close to what I want, it kind of explains what to do, but doesn't really help a beginner like myself to actually do it.

Here's my Control Flow for reference:

And the Main method within the script task:

```<code>ArrayList messages = new ArrayList();

try
{
    messages = (ArrayList) Dts.Variables["ErrorCollection"].Value;
}
catch (Exception Ex)
{
    // Handle errors...
}

messages.Add(Dts.Variables["ErrorDescription"].Value.ToString());
Dts.Variables["ErrorCollection"].Value = messages;
Dts.Variables.Unlock();
Dts.TaskResult = (int)ScriptResults.Success;
</code>```

I don't know whether I'm going about this the wrong way, there's probably an easy way to do this but being new to SSIS I don't know what it is. Any help will be appreciated. Thanks!

答:
Right, I managed to figure it out on my own. For anyone facing a similar problem, here's how I went about it:

Set up a variable for each task you want to monitor - this could be a 1 or 0 for success/failure. In my case I set the variables for each task to a default success message string.

Apply an OnError event handler to each task you want to monitor

Place an Expression Task within the OnError handler and use it to set your variable to the fail condition. E.g. @[User:YourVariable] = "Failed"

Within a Send Mail Task you can concatenate each of the variables you created earlier for the MessageSource within the Expressions tab of the Send Mail Task editor.

This solution skips the Script Task altogether, but if you wanted to build up a more detailed email message, you could pass the variables to a Script instead of straight into the Send Mail Task.

Body:
I've got a simple package which updates my database then exports data to five different files. What I'm trying to do is produce an email which details whether each of the exports have run successfully. So I want something like this in the email:

|EXPORT | STATUS  |
| 4     | Success |
| 5     | Success |
| 6     | Success |
| 7     | Failed  |
| 8     | Success |

Initially, I had separate Success and Fail (Logical OR) email tasks set up. This allowed me to determine that either all the tasks succeeded or at least one failed... but that wasn't what I wanted.

Then, I looked at this example and rewriting it in C# within my script task, but I realised that the variables in the example didn't seem to exist (script would throw an error), so I tried creating user variables and passing them through in the ReadWriteVariables, the script would run successfully but nothing would be displayed in the Send Mail Task, the the script wasn't actually doing anything.

I've looked at a few similar questions and this one seems to be close to what I want, it kind of explains what to do, but doesn't really help a beginner like myself to actually do it.

Here's my Control Flow for reference:

And the Main method within the script task:

ArrayList messages = new ArrayList();

try
{
    messages = (ArrayList) Dts.Variables["ErrorCollection"].Value;
}
catch (Exception Ex)
{
    // Handle errors...
}

messages.Add(Dts.Variables["ErrorDescription"].Value.ToString());
Dts.Variables["ErrorCollection"].Value = messages;
Dts.Variables.Unlock();
Dts.TaskResult = (int)ScriptResults.Success;

I don't know whether I'm going about this the wrong way, there's probably an easy way to do this but being new to SSIS I don't know what it is. Any help will be appreciated. Thanks!


问:
How to write an entity comparator in C# (with example code of first attempt)

Possible Duplicate:

  What is the best way to compare two entity framework entities?

I want to know the most efficient way of comparing two entities of the same type.

One entity is created from an xml file by hand ( ie new instance and manually set properties) and the other is retvied from my object context.

I want to know if the property values are the same in each instance.

My first thoughts are to generate a hash of the property values from each object and compare the hashes, but there might be another way, or a built in way?

Any suggestions would be welcome.

Many thanks,

James

UPDATE

I came up with this:

```<code>static class ObjectComparator<T>
{
    static bool CompareProperties(T newObject, T oldObject)
    {
        if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
        {
            return false;
        }
        else
        {
            var oldProperties = oldObject.GetType().GetProperties();

            foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

                    if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
    }
}
</code>```

I haven't tested it yet, it is more of a food for thought to generate some more ideas from the group.

One thing that might be a problem is comparing properties that have entity values themselves, if the default comparator compares on object reference then it will never be true. A possible fix is to overload the equality operator on my entities so that it compares on entity ID.

答:
I would do something like this</p>

```<code>static class ObjectComparator<T>
{
    public static bool CompareProperties(T newObject, T oldObject)
    {
        if (Equals(newObject, oldObject))
        {
            return true;
        }
        PropertyInfo[] newProps = newObject.GetType().GetProperties();
        PropertyInfo[] oldProps = oldObject.GetType().GetProperties();

        if (newProps.Length != oldProps.Length)
        {
            return false;
        }

        foreach (PropertyInfo newProperty in newProps)
        {
            PropertyInfo oldProperty = oldProps.SingleOrDefault(pi => pi.Name == newProperty.Name);
            if (oldProperty == null)
                return false;

            object newval = newProperty.GetValue(newObject, null);
            object oldval = oldProperty.GetValue(oldObject, null);

            if (!Equals(newval, oldval))
                return false;
        }
        return true;
    }
}
</code>```

Body:
Possible Duplicate:

  What is the best way to compare two entity framework entities?

I want to know the most efficient way of comparing two entities of the same type.

One entity is created from an xml file by hand ( ie new instance and manually set properties) and the other is retvied from my object context.

I want to know if the property values are the same in each instance.

My first thoughts are to generate a hash of the property values from each object and compare the hashes, but there might be another way, or a built in way?

Any suggestions would be welcome.

Many thanks,

James

UPDATE

I came up with this:

static class ObjectComparator<T>
{
    static bool CompareProperties(T newObject, T oldObject)
    {
        if (newObject.GetType().GetProperties().Length != oldObject.GetType().GetProperties().Length)
        {
            return false;
        }
        else
        {
            var oldProperties = oldObject.GetType().GetProperties();

            foreach (PropertyInfo newProperty in newObject.GetType().GetProperties())
            {
                try
                {
                    PropertyInfo oldProperty = oldProperties.Single<PropertyInfo>(pi => pi.Name == newProperty.Name);

                    if (newProperty.GetValue(newObject, null) != oldProperty.GetValue(oldObject, null))
                    {
                        return false;
                    }
                }
                catch
                {
                    return false;
                }
            }

            return true;
        }
    }
}

I haven't tested it yet, it is more of a food for thought to generate some more ideas from the group.

One thing that might be a problem is comparing properties that have entity values themselves, if the default comparator compares on object reference then it will never be true. A possible fix is to overload the equality operator on my entities so that it compares on entity ID.

Body:
I would do something like this

static class ObjectComparator<T>
{
    public static bool CompareProperties(T newObject, T oldObject)
    {
        if (Equals(newObject, oldObject))
        {
            return true;
        }
        PropertyInfo[] newProps = newObject.GetType().GetProperties();
        PropertyInfo[] oldProps = oldObject.GetType().GetProperties();

        if (newProps.Length != oldProps.Length)
        {
            return false;
        }

        foreach (PropertyInfo newProperty in newProps)
        {
            PropertyInfo oldProperty = oldProps.SingleOrDefault(pi => pi.Name == newProperty.Name);
            if (oldProperty == null)
                return false;

            object newval = newProperty.GetValue(newObject, null);
            object oldval = oldProperty.GetValue(oldObject, null);

            if (!Equals(newval, oldval))
                return false;
        }
        return true;
    }
}

ContentLicense: CC BY-SA 2.5


问:
Only Alphabet and whitespace allowed in UITextField Swift
I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

```<code>//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }

ex: nameValue : "abcd" it works, but
if nameValue : "ab cd" whitespace included, it returns the showAlert message.
</code>```

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

Thank you .

答:
Use regex:

```<code>let regex = try! NSRegularExpression(pattern: "[a-zA-Z\\s]+", options: [])
</code>```

You can match it like this:

```<code>let range = regex.rangeOfFirstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
return range.length == string.characters.count
</code>```

Body:
I want to validate my textField that check only Alphabet & whitespace allowed, If number was given then it will return warning error.

//First I declare my value to variable
var nameValue: String = mainView.nameTextField.text!

//Then I declare this
 let set = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLKMNOPQRSTUVWXYZ")

//And this is the validation
if(nameValue.rangeOfCharacter(from: set.inverted) != nil ){
    self.showAlert(message: "Must not contain Number in Name")
   } else {
      //other code
   }

ex: nameValue : "abcd" it works, but
if nameValue : "ab cd" whitespace included, it returns the showAlert message.

This code works but only for alphabets, What I need now is alphabets and a whitespace. and what I declare was a hardcode I guess. Maybe you guys have better code and options for this case.

Thank you .

Body:
Use regex:

let regex = try! NSRegularExpression(pattern: "[a-zA-Z\\s]+", options: [])

You can match it like this:

let range = regex.rangeOfFirstMatch(in: string, options: [], range: NSRange(location: 0, length: string.characters.count))
return range.length == string.characters.count


问:
OTA_AirPriceRQ in Sabre AIr booking
Can any one help me on the OTA_AirPriceRQ request. I want to know the options which I can include with it so that i can get a success response.</p>

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://schemas.xmlsoap.org/ws/2002/12/secext" xmlns:mes="http://www.ebxml.org/namespaces/messageHeader" xmlns:v3="http://services.sabre.com/sp/eab/v3_7">
       <soapenv:Header>
          <sec:Security>
              <sec:BinarySecurityToken>Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!-3273332406989210493!448034!0!1</sec:BinarySecurityToken>
      </sec:Security>
      <mes:MessageHeader >
         <mes:From>
            <!--1 or more repetitions:-->
                        <mes:PartyId mes:type="urn:x12.org:IO5:01">Traform</mes:PartyId>
                   </mes:From>
         <mes:To>
            <!--1 or more repetitions:-->
           <mes:PartyId mes:type="urn:x12.org:IO5:01">Sabre</mes:PartyId>

         </mes:To>
         <mes:CPAId>VJ6I</mes:CPAId>
<mes:ConversationId>Traform</mes:ConversationId>
                  <mes:Service mes:type="OTA">EnhancedAirBookRQ</mes:Service>
       <mes:Action>EnhancedAirBookRQ</mes:Action>
         <mes:MessageData>
           <mes:MessageId>1000</mes:MessageId>
            <mes:Timestamp>2017-05-22T17:28</mes:Timestamp>
                   </mes:MessageData>
      </mes:MessageHeader>
   </soapenv:Header>
<soapenv:Body>
      <v3:EnhancedAirBookRQ xmlns="http://services.sabre.com/sp/eab/v3_7" version="3.7.0" HaltOnError="true">

         <v3:OTA_AirBookRQ>

            <v3:OriginDestinationInformation>

               <v3:FlightSegment  DepartureDateTime="2017-11-21T17:05" FlightNumber="9392"
               NumberInParty="1"
               ResBookDesigCode="F" Status="QF">
                  <v3:DestinationLocation LocationCode="LHR"/>

                  <v3:MarketingAirline Code="MH" FlightNumber="9392"/>

                  <v3:OriginLocation LocationCode="DFW"/>
               </v3:FlightSegment>
            </v3:OriginDestinationInformation>

<RedisplayReservation NumAttempts="2" WaitInterval="5000"/>
         </v3:OTA_AirBookRQ>
<v3:OTA_AirPriceRQ>
        <v3:PriceRequestInformation Retain="true">
          <v3:OptionalQualifiers>
            <v3:PricingQualifiers>
            <PassengerType Code="ADT" Quantity="1" />

              </v3:PricingQualifiers>
 </v3:OptionalQualifiers>
        </v3:PriceRequestInformation>
      </v3:OTA_AirPriceRQ>
      </v3:EnhancedAirBookRQ>

   </soapenv:Body>
</soapenv:Envelope>
</code>```

答:
```<code>See below complete Enhanced Air Book request
<?xml version="1.0" encoding="UTF-8"?>
    <EnhancedAirBookRQ version="3.7.0" HaltOnError="true">
       <OTA_AirBookRQ xmlns="http://services.sabre.com/sp/eab/v3_7">
          <HaltOnStatus Code="NN" />
          <HaltOnStatus Code="UC" />
          <HaltOnStatus Code="NO" />
          <HaltOnStatus Code="US" />
          <OriginDestinationInformation>
             <FlightSegment DepartureDateTime="2017-06-01T15:40" FlightNumber="4793" NumberInParty="2" ResBookDesigCode="K" Status="NN">
                <DestinationLocation LocationCode="CDG" />
                <Equipment AirEquipType="77W" />
                <MarketingAirline Code="9W" FlightNumber="639" />
                <MarriageGrp>O</MarriageGrp>
                <OperatingAirline Code="AF" />
                <OriginLocation LocationCode="IAH" />
             </FlightSegment>
             <FlightSegment DepartureDateTime="2017-06-02T11:35" FlightNumber="123" NumberInParty="2" ResBookDesigCode="K" Status="NN">
                <DestinationLocation LocationCode="BOM" />
                <Equipment AirEquipType="333" />
                <MarketingAirline Code="9W" FlightNumber="123" />
                <MarriageGrp>I</MarriageGrp>
                <OperatingAirline Code="9W" />
                <OriginLocation LocationCode="CDG" />
             </FlightSegment>
             <FlightSegment DepartureDateTime="2017-06-03T05:30" FlightNumber="341" NumberInParty="2" ResBookDesigCode="K" Status="NN">
                <DestinationLocation LocationCode="BDQ" />
                <Equipment AirEquipType="738" />
                <MarketingAirline Code="9W" FlightNumber="341" />
                <MarriageGrp>I</MarriageGrp>
                <OperatingAirline Code="9W" />
                <OriginLocation LocationCode="BOM" />
             </FlightSegment>
             <FlightSegment DepartureDateTime="2017-06-06T20:55" FlightNumber="344" NumberInParty="2" ResBookDesigCode="O" Status="NN">
                <DestinationLocation LocationCode="BOM" />
                <Equipment AirEquipType="738" />
                <MarketingAirline Code="9W" FlightNumber="344" />
                <MarriageGrp>O</MarriageGrp>
                <OperatingAirline Code="9W" />
                <OriginLocation LocationCode="BDQ" />
             </FlightSegment>
             <FlightSegment DepartureDateTime="2017-06-07T02:25" FlightNumber="3288" NumberInParty="2" ResBookDesigCode="V" Status="NN">
                <DestinationLocation LocationCode="AMS" />
                <Equipment AirEquipType="333" />
                <MarketingAirline Code="9W" FlightNumber="3288" />
                <MarriageGrp>I</MarriageGrp>
                <OperatingAirline Code="9W" />
                <OriginLocation LocationCode="BOM" />
             </FlightSegment>
             <FlightSegment DepartureDateTime="2017-06-07T10:00" FlightNumber="8803" NumberInParty="2" ResBookDesigCode="V" Status="NN">
                <DestinationLocation LocationCode="IAH" />
                <Equipment AirEquipType="74E" />
                <MarketingAirline Code="9W" FlightNumber="661" />
                <MarriageGrp>I</MarriageGrp>
                <OperatingAirline Code="KL" />
                <OriginLocation LocationCode="AMS" />
             </FlightSegment>
          </OriginDestinationInformation>
          <RedisplayReservation NumAttempts="2" WaitInterval="5000" />
       </OTA_AirBookRQ>
       <OTA_AirPriceRQ xmlns="http://services.sabre.com/sp/eab/v3_7">
          <PriceRequestInformation Retain="true">
             <OptionalQualifiers>
                <FlightQualifiers>
                   <VendorPrefs>
                      <Airline Code="9W" />
                   </VendorPrefs>
                </FlightQualifiers>
                <MiscQualifiers>
                   <Commission Amount="0.00" />
                </MiscQualifiers>
                <PricingQualifiers CurrencyCode="USD">
                   <PassengerType Code="ADT" Quantity="1" />
                   <PassengerType Code="INF" Quantity="1" />
                   <PassengerType Code="CNN" Quantity="1" />
                </PricingQualifiers>
             </OptionalQualifiers>
          </PriceRequestInformation>
       </OTA_AirPriceRQ>
       <PostProcessing xmlns="http://services.sabre.com/sp/eab/v3_7">
          <RedisplayReservation WaitInterval="5000" UnmaskCreditCard="true" />
       </PostProcessing>
    </EnhancedAirBookRQ>
</code>```

Title: OTA_AirPriceRQ in Sabre AIr booking

Body:
Can any one help me on the OTA_AirPriceRQ request. I want to know the options which I can include with it so that i can get a success response.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sec="http://schemas.xmlsoap.org/ws/2002/12/secext" xmlns:mes="http://www.ebxml.org/namespaces/messageHeader" xmlns:v3="http://services.sabre.com/sp/eab/v3_7">
       <soapenv:Header>
          <sec:Security>
              <sec:BinarySecurityToken>Shared/IDL:IceSess\/SessMgr:1\.0.IDL/Common/!ICESMS\/ACPCRTC!ICESMSLB\/CRT.LB!-3273332406989210493!448034!0!1</sec:BinarySecurityToken>
      </sec:Security>
      <mes:MessageHeader >
         <mes:From>

                        <mes:PartyId mes:type="urn:x12.org:IO5:01">Traform</mes:PartyId>
                   </mes:From>
         <mes:To>

           <mes:PartyId mes:type="urn:x12.org:IO5:01">Sabre</mes:PartyId>

         </mes:To>
         <mes:CPAId>VJ6I</mes:CPAId>
<mes:ConversationId>Traform</mes:ConversationId>
                  <mes:Service mes:type="OTA">EnhancedAirBookRQ</mes:Service>
       <mes:Action>EnhancedAirBookRQ</mes:Action>
         <mes:MessageData>
           <mes:MessageId>1000</mes:MessageId>
            <mes:Timestamp>2017-05-22T17:28</mes:Timestamp>
                   </mes:MessageData>
      </mes:MessageHeader>
   </soapenv:Header>
<soapenv:Body>
      <v3:EnhancedAirBookRQ xmlns="http://services.sabre.com/sp/eab/v3_7" version="3.7.0" HaltOnError="true">

         <v3:OTA_AirBookRQ>

            <v3:OriginDestinationInformation>

               <v3:FlightSegment  DepartureDateTime="2017-11-21T17:05" FlightNumber="9392"
               NumberInParty="1"
               ResBookDesigCode="F" Status="QF">
                  <v3:DestinationLocation LocationCode="LHR"/>

                  <v3:MarketingAirline Code="MH" FlightNumber="9392"/>

                  <v3:OriginLocation LocationCode="DFW"/>
               </v3:FlightSegment>
            </v3:OriginDestinationInformation>

<RedisplayReservation NumAttempts="2" WaitInterval="5000"/>
         </v3:OTA_AirBookRQ>
<v3:OTA_AirPriceRQ>
        <v3:PriceRequestInformation Retain="true">
          <v3:OptionalQualifiers>
            <v3:PricingQualifiers>
            <PassengerType Code="ADT" Quantity="1" />

              </v3:PricingQualifiers>
 </v3:OptionalQualifiers>
        </v3:PriceRequestInformation>
      </v3:OTA_AirPriceRQ>
      </v3:EnhancedAirBookRQ>

   </soapenv:Body>
</soapenv:Envelope>


问:
Height issue with elements in a row using flexbox and scrolling
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

```<code><section>
    <div> <!-- very long content --> </div>
    <div>b</div>
    ....
</section>
</code>```

CSS:

```<code>section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}
</code>```

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?

答:
Use height:auto; style instead of fixed height
see fiddle

```<code>section {
    display: flex;
    border: 2px solid red;
    height: auto;
    align-items: stretch;
    overflow:auto;
}
div {
    background-color: green;
    margin: 5px;
    flex: 1;
}
</code>```

Or you can avoid height style as in updated fiddle

Body:
I have a couple of element which are positioned horizontally, but they are taller than the parent, meeaning they scroll. It looks like this

Although the scroll behaviour is correct, the content of the first block overflows.

The HTML looks like this

b

    ....

CSS:

section {
    display: flex;
    border: 2px solid red;
    height: 100px;
    align-items: stretch;
    overflow:auto;
}

div {
    background-color: green;
    margin: 5px;
    flex: 1;
}

DEMO

As you can see in the demo, the element with the green background color is not tall enough to fit all the content. How can this be achieved ? It would be nice if all divs have the same height, is that possible?

Body:
Use height:auto; style instead of fixed height
see fiddle

section {
    display: flex;
    border: 2px solid red;
    height: auto;
    align-items: stretch;
    overflow:auto;
}
div {
    background-color: green;
    margin: 5px;
    flex: 1;
}

Or you can avoid height style as in updated fiddle


问:
BigCommerce PHP hello world app installation error
I am trying to create a BigCommerce app and used hello world app from here >> https://github.com/bigcommerce/hello-world-app-php-silex

As per its documentation, I have to write localhost URL in callback URL. I have done the same, but when I am trying to install app from my trial store, I am getting error in console and the page shows installing....

Console error is:

Mixed Content: The page was loaded over HTTPS, but requested an insecure form action 'http://localhost/hello-test/auth/callback?shipping_read_only+store_v2_transactions_read_only+users_basic_information'. This request has been blocked; the content must be served over HTTPS.

Due to this error, I can not install my app and can not start developing on it. Please help

答: The error seems obvious to me, you have an HTTPS issue. You have to put you website in SSL mode with a certificate. </p>


问:
Docfx, how can make it render correctly accents characters?
I'm compiling a documentation with DocFx from Visual Studio with the NuGet package.

I write in Italian and we have a lot of characters like: à è ì ò ù. In the final render, my page looks like this:

The final html looks like this:

How can I make it render correctly?

答: I solved the issue saving the .md file with UTF-8 (without BOM) encoding.