问:
Searching for numbers/product codes in Solr
I have a text-field to which i'm feeding normal text that contains product codes (e.g. FI302010, RR220011, etc).
I would like to be able to search for these product numbers.
I have tried it out in the ANALYSIS-tool - And here it looks like it should be possible. A standard text-field does some word delimiting that splits the product codes into "FI" and "302010" - but as long as the same happens in both query and index it shouldn't be a problem.
When i look at the schema browser i cant find the product codes, but i can find something that looks like a stemmed version of the code (i.e. 30201 - the last 0 is missing).

I have tried using different text-types (text_ws, textTight and text) - but none will allow me to do the search.

How should I enable text-search in text?

Thanks

答:
This actually just works with the example configuration.

Taking stock Solr 1.4.1, and running the example config, you can see that, as you said, the analysis tool shows that this works for a stock text field.

Then, to verify, note that the "features" field in the example schema is of type text. Edit one of the sample files in apache-solr-1.4.1/example/exampledocs. Say "monitor.xml". Add the product code to the features field of one document. (and a space on either side)

Post the file to Solr (using java -jar post.jar monitor.xml). Now go search for it. It works. Check the schema browser. Show all the terms in the features field. Notice that the number is there by itself in a term.

It all works for me.

Not sure what happened to your schema browswer, perhaps a typo? Numbers aren't stemmed. It that trailing character is an o (letter) not a zero, that might be your problem.

Using keywordtokenizer will not allow you to find the numeric part of the product code, which was the original question.


来源: stackexchange

问:
Two different variables getting same value
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

```<code>public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}
</code>```

Here I am using the variables:

```<code>MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());
</code>```

The output is the following: http://imgur.com/a/Nu3N6

答:
You need to know about static and local variables.

Static variables of a class are such variables which are common to all instances of that class and are shared by all of the instances. E.g. if I have a class:

```<code>public static class myClass{
    public static int staticVar;

    //Constructor
    public myClass(){
        staticVar = 0;
    }
 }
</code>```

and then I have the following code in a main method of another class:

```<code>public static void main(String args[]){
    myClass c1, c2;
    c1 = new myClass();
    c2 = new myClass();
    c1.staticVar = 4;
    c2.staticVar = 8;
    System.out.println(c1.staticVar + " " + c2.staticVar);
}
</code>```

then my output will be:

```<code>8 8
</code>```

This is because the variable staticVar is shared by both c1 and c2. First when the statement c1.staticVar = 4 is executed, the value of staticVar for both c1 and c2 is 4. Then the statement c2.staticVar = 8 is executed to change the value of staticVar of both classes to 8.

So in your problem, you have to make your name and path variables non-static to give each of your myFile instances a different value of the variables.

I hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I am currently working on a small Java application and I ran into a problem. I create two different variables, but after I run the code, the first variable is getting the same value as the second one. They should be different.

Here is my custom file class:

public class MyFile {

    private static String path;
    private static String name;

    private static final String FILE_SEPARATOR = "/";

    public MyFile(String path) {
        System.out.println(path);
        this.path = "";
        this.name = "";
        this.path = /*FILE_SEPARATOR*/path;
        String[] dirs = path.split(FILE_SEPARATOR);
        this.name = dirs[dirs.length - 1];
    }

    public static String getPath() {
        return path;
    }

    public static String getName() {
        return name;
    }

    public String toString() {
        return "Path: " + path + ", Name: " + name;
    }
}

Here I am using the variables:

MyFile modelFile = new MyFile("res\\model.dae");
MyFile textureFile = new MyFile("res\\diffuse.png");
System.out.println(modelFile.toString());
System.out.println(textureFile.toString());

The output is the following: http://imgur.com/a/Nu3N6

Body:
You need to know about static and local variables.

Static variables of a class are such variables which are common to all instances of that class and are shared by all of the instances. E.g. if I have a class:

public static class myClass{
    public static int staticVar;

    //Constructor
    public myClass(){
        staticVar = 0;
    }
 }

and then I have the following code in a main method of another class:

public static void main(String args[]){
    myClass c1, c2;
    c1 = new myClass();
    c2 = new myClass();
    c1.staticVar = 4;
    c2.staticVar = 8;
    System.out.println(c1.staticVar + " " + c2.staticVar);
}

then my output will be:

8 8

This is because the variable staticVar is shared by both c1 and c2. First when the statement c1.staticVar = 4 is executed, the value of staticVar for both c1 and c2 is 4. Then the statement c2.staticVar = 8 is executed to change the value of staticVar of both classes to 8.

So in your problem, you have to make your name and path variables non-static to give each of your myFile instances a different value of the variables.

I hope this helps.


问:
How do I get properties that ONLY have populated values?
How do I get properties that ONLY have populated values?

So for example if I run

```<code>Get-QADUser -Identity "SomeOne" -IncludeAllProperties
</code>```

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

答:
You first get its properties (since Get-QADUser depends on AD schema, the properties list is dynamic) with get-member -type property, then filter out those that don't have \{.*(get).*\} in its definition (that is, they are not "gettable"), then enumerate the resultant list by name and filter out nulls.

```<code>$someone=Get-QADUser -Identity "SomeOne" -IncludeAllProperties
$members=$someone|get-member -type property| where {$_.definition -match '\{.*(get).*\}'}
foreach ($member in $members) {
    if ($someone[$member.name] -ne $null) {
        write-host $member.name $someone[$member.name]
    }
}
</code>```

Body:
How do I get properties that ONLY have populated values?

So for example if I run

Get-QADUser -Identity "SomeOne" -IncludeAllProperties

the output would of course include.. all properties, including those with and those without values. I want a listing of properties with values only. How is it done generally speaking?

This wouldn't be restricted to Quest Cmdlets, I only use Get-QADUser as an example.

Body:
You first get its properties (since Get-QADUser depends on AD schema, the properties list is dynamic) with get-member -type property, then filter out those that don't have \{.*(get).*\} in its definition (that is, they are not "gettable"), then enumerate the resultant list by name and filter out nulls.

$someone=Get-QADUser -Identity "SomeOne" -IncludeAllProperties
$members=$someone|get-member -type property| where {$_.definition -match '\{.*(get).*\}'}
foreach ($member in $members) {
    if ($someone[$member.name] -ne $null) {
        write-host $member.name $someone[$member.name]
    }
}


问:
JQuery Multi Step Form - Go back to first step once close
How can I go back to the first of my multi-step form once the modal is closed?

I managed to reset the percentage to its original number, but not the form.

Here's my Multi-step JavaScript :

```<code>/**
* Created by admin on 20/05/2017.
*/
$(document).ready(function(){
var current = 1;

widget      = $(".step");
btnnext     = $(".next");
btnback     = $(".back");
btnsubmit   = $(".submit");

// Init buttons and UI
widget.not(':eq(0)').hide();
hideButtons(current);
setProgress(current);

// Next button click action
btnnext.click(function(){
    if(current < widget.length){
        // Check validation
        if($("#register-form").valid()){
            widget.show();
            widget.not(':eq('+(current++)+')').hide();
            setProgress(current);
        }
    }
    hideButtons(current);
});

// Back button click action
btnback.click(function(){
    if(current > 1){
        current = current - 2;
        if(current < widget.length){
            widget.show();
            widget.not(':eq('+(current++)+')').hide();
            setProgress(current);
        }
    }
    hideButtons(current);
})
</code>```

});

```<code>// Change progress bar action
setProgress = function(currstep){
var percent = parseFloat(100 / widget.length) * currstep;
/*
 * 100/TheNumberOfWidget * TheCurrentOne
 * If we remove the current one (currstep), the progress bar won't increase.
 */
percent = percent.toFixed();
$(".progress-bar").css("width",percent+"%").html(percent+"%");
// Simply show % in the progress-bar class.
</code>```

};

```<code>// Hide buttons according to the current step
hideButtons = function(current){
var limit = parseInt(widget.length);
/*
 * limit = The nubmer of the widget, and it is a integer value.
 */

$(".action").hide();
// Hide the buttons

if(current < limit) btnnext.show();
/*
 * If there is at least one widget after the current one :
 * it will show next
 */
if(current > 1) btnback.show();
/*
 * If there is at least one widget before the current one :
 * it will show back
 */
if (current === limit) {
    // Show entered values when we reached the the last widget form.
    $(".display label:not(.control-label)").each(function(){
        console.log($(this).parent().find("label:not(.control-label)").html($("#"+$(this).data("id")).val()));
    });
    btnnext.hide();
    btnsubmit.show();
}
};
</code>```

Here is my form

```<code>    <!-- Modal Register -->
<div class="modal fade modal-ext modal-register" id="modal-register" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <!-- Modal Register | Container -->
        <div class="modal-content">
            <!-- Modal Register | Form-->
            <form method="post" role="form" id="register-form" autocomplete="off">
                <!-- Modal Register | Title -->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">Sign up</h4>
                </div>
                <!--/.Modal Register | Title -->

                <!-- Modal Register | Content -->
                <div class="modal-body">

                    <!-- json response will be here -->
                    <div id="error_register"></div>
                    <!-- json response will be here -->

                    <div class="progress">
                        <div class="progress-bar progress-bar-custom progress-bar-striped active" role="progressbar"
                             aria-valuemin="0" aria-valuemax="100"></div>
                    </div>

                    <!-- Modal Register | Firstname -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="firstname" name="firstname" class="form-control" required>
                            <label for="firstname">Firstname</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Lastname -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-circle prefix"></i>
                            <input type="text" id="lastname" name="lastname" class="form-control" required>
                            <label for="lastname">Lastname</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Username -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="username" name="username" class="form-control" required>
                            <label for="username">Username</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Password -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-lock prefix"></i>
                            <input type="password" id="password" name="password" class="form-control" required>
                            <label for="password">Password</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Retype Password -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-asterisk prefix"></i>
                            <input type="password" id="cpassword" name="cpassword" class="form-control" required>
                            <label for="cpassword">Retype Password</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Email -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-envelope prefix"></i>
                            <input type="email" id="email" name="email" class="form-control"
                                   pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+">
                            <label for="email">Mail</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Login | Check -->
                    <?php
                    $number_a = rand(1, 5);
                    $number_b = rand(0, 4);
                    $_SESSION['register_valid_operation'] = $number_a + $number_b;
                    ?>
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                        <i class="fa fa-calculator prefix"></i>
                        <input type="text" id="register_result" name="register_result" class="form-control" required>
                        <label for="register_result"><?php echo($number_a) ?> + <?php echo($number_b) ?> = ?</label>
                        <span class="help-block" id="error"></span>
                        </div>
                    </div>
                    <br>
                    <div class="step display">
                        <h5>   Confirm details</h5>
                        <br>
                        <div class="modal_md_form">
                            <div>
                                <label class="col-xs-2 control-label">Firstname</label>
                                <div class="col-xs-10">
                                    <label data-id="firstname"></label>
                                </div>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Lastname</label>
                            <div class="col-xs-10">
                                <label data-id="lastname"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Username</label>
                            <div class="col-xs-10">
                                <label data-id="username"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Email</label>
                            <div class="col-xs-10">
                                <label data-id="email"></label>
                                <br><br>
                            </div>
                        </div>
                    </div>
                    <!-- Modal Register | Send -->
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="pull-left">
                                <button type="button" class="action back btn btn-primary">Back</button>
                                <button type="button" class="action next btn btn-primary">Next</button>
                                <button class="action submit btn btn-primary" id="btn-signup">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!--/.Modal Register | Content -->

                <!--Footer-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
            <!--/.Modal Register | Form-->
        </div>
        <!--/.Modal Register | Container -->
    </div>
</div>
<!--/ Modal Register -->
</code>```

Here is my script to close the modal, reset it and reset the progress bar :

```<code>$('#modal-register').on('shown.bs.modal', function () {
var current = 1;
$("#register-form").trigger('reset');
setProgress(current);
});
</code>```

How can I make it to reset the form to the step 1 (Firstname & Lastname)?

答:
After trying your code, I think you get the wrong close button.

$(document).ready(function () {
    var current = 1;

    widget = $(".step");
    btnnext = $(".next");
    btnback = $(".back");
    btnsubmit = $(".submit");
    btnclose = $(".btn-default");

    // Init buttons and UI
    widget.not(':eq(0)').hide();
    hideButtons(current);
    setProgress(current);

    // Next button click action
    btnnext.click(function () {
        if (current < widget.length) {
            // Check validation
            //if ($("#register-form").valid()) {
                widget.show();
                widget.not(':eq(' + (current++) + ')').hide();
                setProgress(current);
            //}
        }
        hideButtons(current);
    });

    // Back button click action
    btnback.click(function () {
        if (current > 1) {
            current = current - 2;
            if (current < widget.length) {
                widget.show();
                widget.not(':eq(' + (current++) + ')').hide();
                setProgress(current);
            }
        }
        hideButtons(current);
    });

    btnclose.on("click", function() {
        current = 0;
        $("#register-form").trigger("reset");
        btnnext.trigger("click");
    });
});

// Change progress bar action
var setProgress = function (currstep) {
    var percent = parseFloat(100 / widget.length) * currstep;
    /*
     * 100/TheNumberOfWidget * TheCurrentOne
     * If we remove the current one (currstep), the progress bar won't increase.
     */
    percent = percent.toFixed();
    $(".progress-bar").css("width", percent + "%").html(percent + "%");
    // Simply show % in the progress-bar class.
};

// Hide buttons according to the current step
var hideButtons = function (current) {
    var limit = parseInt(widget.length);
    /*
     * limit = The nubmer of the widget, and it is a integer value.
     */

    $(".action").hide();
    // Hide the buttons

    if (current < limit) btnnext.show();
    /*
     * If there is at least one widget after the current one :
     * it will show next
     */
    if (current > 1) btnback.show();
    /*
     * If there is at least one widget before the current one :
     * it will show back
     */
    if (current === limit) {
        btnnext.hide();
        btnsubmit.show();
    }
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade modal-ext modal-register" id="modal-register" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <!-- Modal Register | Container -->
        <div class="modal-content">
            <!-- Modal Register | Form-->
            <form method="post" role="form" id="register-form" autocomplete="off">
                <!-- Modal Register | Title -->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">×</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">Sign up</h4>
                </div>
                <!--/.Modal Register | Title -->

                <!-- Modal Register | Content -->
                <div class="modal-body">

                    <!-- json response will be here -->
                    <div id="error_register"></div>
                    <!-- json response will be here -->

                    <div class="progress">
                        <div class="progress-bar progress-bar-custom progress-bar-striped active" role="progressbar"
                             aria-valuemin="0" aria-valuemax="100"></div>
                    </div>

                    <!-- Modal Register | Firstname -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="firstname" name="firstname" class="form-control" required>
                            <label for="firstname">Firstname</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Lastname -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-circle prefix"></i>
                            <input type="text" id="lastname" name="lastname" class="form-control" required>
                            <label for="lastname">Lastname</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Username -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="username" name="username" class="form-control" required>
                            <label for="username">Username</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Password -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-lock prefix"></i>
                            <input type="password" id="password" name="password" class="form-control" required>
                            <label for="password">Password</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Retype Password -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-asterisk prefix"></i>
                            <input type="password" id="cpassword" name="cpassword" class="form-control" required>
                            <label for="cpassword">Retype Password</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Email -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-envelope prefix"></i>
                            <input type="email" id="email" name="email" class="form-control"
                                   pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+">
                            <label for="email">Mail</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                        <i class="fa fa-calculator prefix"></i>
                        <input type="text" id="register_result" name="register_result" class="form-control" required>
                        <label for="register_result"><?php echo($number_a) ?> + <?php echo($number_b) ?> = ?</label>
                        <span class="help-block" id="error"></span>
                        </div>
                    </div>
                    <br>
                    <div class="step display">
                        <h5>   Confirm details</h5>
                        <br>
                        <div class="modal_md_form">
                            <div>
                                <label class="col-xs-2 control-label">Firstname</label>
                                <div class="col-xs-10">
                                    <label data-id="firstname"></label>
                                </div>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Lastname</label>
                            <div class="col-xs-10">
                                <label data-id="lastname"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Username</label>
                            <div class="col-xs-10">
                                <label data-id="username"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Email</label>
                            <div class="col-xs-10">
                                <label data-id="email"></label>
                                <br><br>
                            </div>
                        </div>
                    </div>
                    <!-- Modal Register | Send -->
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="pull-left">
                                <button type="button" class="action back btn btn-primary">Back</button>
                                <button type="button" class="action next btn btn-primary">Next</button>
                                <button class="action submit btn btn-primary" id="btn-signup">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!--/.Modal Register | Content -->

                <!--Footer-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
            <!--/.Modal Register | Form-->
        </div>
        <!--/.Modal Register | Container -->
    </div>
</div></code>```

Body:
How can I go back to the first of my multi-step form once the modal is closed?

I managed to reset the percentage to its original number, but not the form.

Here's my Multi-step JavaScript :

/**
* Created by admin on 20/05/2017.
*/
$(document).ready(function(){
var current = 1;

widget      = $(".step");
btnnext     = $(".next");
btnback     = $(".back");
btnsubmit   = $(".submit");

// Init buttons and UI
widget.not(':eq(0)').hide();
hideButtons(current);
setProgress(current);

// Next button click action
btnnext.click(function(){
    if(current < widget.length){
        // Check validation
        if($("#register-form").valid()){
            widget.show();
            widget.not(':eq('+(current++)+')').hide();
            setProgress(current);
        }
    }
    hideButtons(current);
});

// Back button click action
btnback.click(function(){
    if(current > 1){
        current = current - 2;
        if(current < widget.length){
            widget.show();
            widget.not(':eq('+(current++)+')').hide();
            setProgress(current);
        }
    }
    hideButtons(current);
})

});

// Change progress bar action
setProgress = function(currstep){
var percent = parseFloat(100 / widget.length) * currstep;
/*
 * 100/TheNumberOfWidget * TheCurrentOne
 * If we remove the current one (currstep), the progress bar won't increase.
 */
percent = percent.toFixed();
$(".progress-bar").css("width",percent+"%").html(percent+"%");
// Simply show % in the progress-bar class.

};

// Hide buttons according to the current step
hideButtons = function(current){
var limit = parseInt(widget.length);
/*
 * limit = The nubmer of the widget, and it is a integer value.
 */

$(".action").hide();
// Hide the buttons

if(current < limit) btnnext.show();
/*
 * If there is at least one widget after the current one :
 * it will show next
 */
if(current > 1) btnback.show();
/*
 * If there is at least one widget before the current one :
 * it will show back
 */
if (current === limit) {
    // Show entered values when we reached the the last widget form.
    $(".display label:not(.control-label)").each(function(){
        console.log($(this).parent().find("label:not(.control-label)").html($("#"+$(this).data("id")).val()));
    });
    btnnext.hide();
    btnsubmit.show();
}
};

Here is my form

            <form method="post" role="form" id="register-form" autocomplete="off">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        ×
                    </button>

Sign up

                            <input type="text" id="firstname" name="firstname" class="form-control" required>
                            Firstname

                            <input type="text" id="lastname" name="lastname" class="form-control" required>
                            Lastname

                            <input type="text" id="username" name="username" class="form-control" required>
                            Username

                            <input type="password" id="password" name="password" class="form-control" required>
                            Password

                            <input type="password" id="cpassword" name="cpassword" class="form-control" required>
                            Retype Password

                            <input type="email" id="email" name="email" class="form-control"
                                   pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+">
                            Mail

                    <?php
                    $number_a = rand(1, 5);
                    $number_b = rand(0, 4);
                    $_SESSION['register_valid_operation'] = $number_a + $number_b;
                    ?>

                        <input type="text" id="register_result" name="register_result" class="form-control" required>
                        <?php echo($number_a) ?> + <?php echo($number_b) ?> = ?

   Confirm details

                                Firstname

                            Lastname

                            Username

                            Email

                                <button type="button" class="action back btn btn-primary">Back</button>
                                <button type="button" class="action next btn btn-primary">Next</button>
                                <button class="action submit btn btn-primary" id="btn-signup">Submit</button>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

            </form>

Here is my script to close the modal, reset it and reset the progress bar :

$('#modal-register').on('shown.bs.modal', function () {
var current = 1;
$("#register-form").trigger('reset');
setProgress(current);
});

How can I make it to reset the form to the step 1 (Firstname & Lastname)?

Body:
After trying your code, I think you get the wrong close button.

$(document).ready(function () {
    var current = 1;

    widget = $(".step");
    btnnext = $(".next");
    btnback = $(".back");
    btnsubmit = $(".submit");
    btnclose = $(".btn-default");

    // Init buttons and UI
    widget.not(':eq(0)').hide();
    hideButtons(current);
    setProgress(current);

    // Next button click action
    btnnext.click(function () {
        if (current < widget.length) {
            // Check validation
            //if ($("#register-form").valid()) {
                widget.show();
                widget.not(':eq(' + (current++) + ')').hide();
                setProgress(current);
            //}
        }
        hideButtons(current);
    });

    // Back button click action
    btnback.click(function () {
        if (current > 1) {
            current = current - 2;
            if (current < widget.length) {
                widget.show();
                widget.not(':eq(' + (current++) + ')').hide();
                setProgress(current);
            }
        }
        hideButtons(current);
    });

    btnclose.on("click", function() {
        current = 0;
        $("#register-form").trigger("reset");
        btnnext.trigger("click");
    });
});

// Change progress bar action
var setProgress = function (currstep) {
    var percent = parseFloat(100 / widget.length) * currstep;
    /*
     * 100/TheNumberOfWidget * TheCurrentOne
     * If we remove the current one (currstep), the progress bar won't increase.
     */
    percent = percent.toFixed();
    $(".progress-bar").css("width", percent + "%").html(percent + "%");
    // Simply show % in the progress-bar class.
};

// Hide buttons according to the current step
var hideButtons = function (current) {
    var limit = parseInt(widget.length);
    /*
     * limit = The nubmer of the widget, and it is a integer value.
     */

    $(".action").hide();
    // Hide the buttons

    if (current < limit) btnnext.show();
    /*
     * If there is at least one widget after the current one :
     * it will show next
     */
    if (current > 1) btnback.show();
    /*
     * If there is at least one widget before the current one :
     * it will show back
     */
    if (current === limit) {
        btnnext.hide();
        btnsubmit.show();
    }
};

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal fade modal-ext modal-register" id="modal-register" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog" role="document">
        <!-- Modal Register | Container -->
        <div class="modal-content">
            <!-- Modal Register | Form-->
            <form method="post" role="form" id="register-form" autocomplete="off">
                <!-- Modal Register | Title -->
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="myModalLabel">Sign up</h4>
                </div>
                <!--/.Modal Register | Title -->

                <!-- Modal Register | Content -->
                <div class="modal-body">

                    <!-- json response will be here -->
                    <div id="error_register"></div>
                    <!-- json response will be here -->

                    <div class="progress">
                        <div class="progress-bar progress-bar-custom progress-bar-striped active" role="progressbar"
                             aria-valuemin="0" aria-valuemax="100"></div>
                    </div>

                    <!-- Modal Register | Firstname -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="firstname" name="firstname" class="form-control" required>
                            <label for="firstname">Firstname</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Lastname -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-circle prefix"></i>
                            <input type="text" id="lastname" name="lastname" class="form-control" required>
                            <label for="lastname">Lastname</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Username -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-user prefix"></i>
                            <input type="text" id="username" name="username" class="form-control" required>
                            <label for="username">Username</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Password -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-lock prefix"></i>
                            <input type="password" id="password" name="password" class="form-control" required>
                            <label for="password">Password</label>
                            <span class="help-block" id="error"></span>
                        </div>

                        <!-- Modal Register | Retype Password -->
                        <div class="md-form modal_md_form">
                            <i class="fa fa-asterisk prefix"></i>
                            <input type="password" id="cpassword" name="cpassword" class="form-control" required>
                            <label for="cpassword">Retype Password</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <!-- Modal Register | Email -->
                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                            <i class="fa fa-envelope prefix"></i>
                            <input type="email" id="email" name="email" class="form-control"
                                   pattern="[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+">
                            <label for="email">Mail</label>
                            <span class="help-block" id="error"></span>
                        </div>
                    </div>

                    <div class="step">
                        <br>
                        <div class="md-form modal_md_form">
                        <i class="fa fa-calculator prefix"></i>
                        <input type="text" id="register_result" name="register_result" class="form-control" required>
                        <label for="register_result"><?php echo($number_a) ?> + <?php echo($number_b) ?> = ?</label>
                        <span class="help-block" id="error"></span>
                        </div>
                    </div>
                    <br>
                    <div class="step display">
                        <h5>&nbsp;&nbsp;&nbsp;Confirm details</h5>
                        <br>
                        <div class="modal_md_form">
                            <div>
                                <label class="col-xs-2 control-label">Firstname</label>
                                <div class="col-xs-10">
                                    <label data-id="firstname"></label>
                                </div>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Lastname</label>
                            <div class="col-xs-10">
                                <label data-id="lastname"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Username</label>
                            <div class="col-xs-10">
                                <label data-id="username"></label>
                            </div>
                        </div>
                        <div class="modal_md_form">
                            <label class="col-xs-2 control-label">Email</label>
                            <div class="col-xs-10">
                                <label data-id="email"></label>
                                <br><br>
                            </div>
                        </div>
                    </div>
                    <!-- Modal Register | Send -->
                    <div class="row">
                        <div class="col-xs-12">
                            <div class="pull-left">
                                <button type="button" class="action back btn btn-primary">Back</button>
                                <button type="button" class="action next btn btn-primary">Next</button>
                                <button class="action submit btn btn-primary" id="btn-signup">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!--/.Modal Register | Content -->

                <!--Footer-->
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </form>
            <!--/.Modal Register | Form-->
        </div>
        <!--/.Modal Register | Container -->
    </div>
</div>


问:
Return results from cursor as table
I work with Postgres9.5. I have an example which successfully returns the results of a cursor as a string (concatenation of rows):
Here is the example:

```<code>CREATE OR REPLACE FUNCTION get_doctor_appoint()
RETURNS TEXT AS $$
DECLARE
Names TEXT DEfault '';
rec_appoint RECORD;
doctor_appoint cursor
FOR SELECT * FROM appointments
where doctorAMKA = (SELECT doctoramka FROM doctor WHERE username='foo@bar.net')
AND t>'2017-4-6 00:00:00' AND t<'2017-5-6 00:00:00';
BEGIN
OPEN doctor_appoint;

LOOP
FETCH doctor_appoint INTO rec_appoint;
EXIT WHEN NOT FOUND;
Names:=Names||','||rec_appoint.t||':'||rec_appoint.patientamka;
END LOOP;
CLOSE doctor_appoint;
RETURN Names;
END; $$
LANGUAGE plpgsql;
</code>```

I would like to return the results as a table but haven't found an example that does that.

答:
You declare the function as RETURNS SETOF text.

For every row you want to return, use RETURN NEXT text_value;.

To end function execution, use RETURN or drop out at the bottom end of the function.

Title: Return results from cursor as table

Body:
I work with Postgres9.5. I have an example which successfully returns the results of a cursor as a string (concatenation of rows):
Here is the example:

CREATE OR REPLACE FUNCTION get_doctor_appoint()
RETURNS TEXT AS $$
DECLARE
Names TEXT DEfault '';
rec_appoint RECORD;
doctor_appoint cursor
FOR SELECT * FROM appointments
where doctorAMKA = (SELECT doctoramka FROM doctor WHERE username='foo@bar.net')
AND t>'2017-4-6 00:00:00' AND t<'2017-5-6 00:00:00';
BEGIN
OPEN doctor_appoint;

LOOP
FETCH doctor_appoint INTO rec_appoint;
EXIT WHEN NOT FOUND;
Names:=Names||','||rec_appoint.t||':'||rec_appoint.patientamka;
END LOOP;
CLOSE doctor_appoint;
RETURN Names;
END; $$
LANGUAGE plpgsql;

I would like to return the results as a table but haven't found an example that does that.


问:
Create an array of primitives or objects in Java

Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

```<code>public void myMethod(Object[] a) {...}
</code>```

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

```<code>public void myMethod(Object[] a) {
     Object something = a[0];
     }
</code>```

答:
All array types are of type Object, nothing more sepecific.</p>

```<code>import java.lang.reflect.Array;

public void myMethod(Object array) {
    Object first = Array.get(a, 0); // Object, primitives are wrapped.
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Can a single Java variable accept an array of either primitives or objects?

I want to create an method that accepts either an arbitrary array. The array can be an array of primitives, or an array of objects.

Unfortunately, I can't do

public void myMethod(Object[] a) {...}

because primitives aren't objects! Is there a way to abstract this one level further?

EDIT I understand that I can pass it as an Object, but then how do I access it as an array within the method? I can't do:

public void myMethod(Object[] a) {
     Object something = a[0];
     }

Body:
All array types are of type Object, nothing more sepecific.

import java.lang.reflect.Array;

public void myMethod(Object array) {
    Object first = Array.get(a, 0); // Object, primitives are wrapped.
}


问:
How to aggregate ElasticSearch documents from same index but from multiple types?
Suppose I have one index (product-index) and multiple types (product, sku, media etc) in that index.

Example documents:

In product-index, product type

```<code>{
  "_type": "product",
  "id": 1,
  "name" : "product 1"
}

{
  "_type": "product",
  "id": 2,
  "name" : "product 2"
}
</code>```

In product-index, sku type

```<code>{
  "_type": "sku",
  "id": 1,
  "name" : "sku 1",
  "product_id": 1
}
{
  "_type": "sku",
  "id": 2,
  "name" : "sku 2",
  "product_id": 1
}

{
  "_type": "sku",
  "id": 3,
  "name" : "sku 3",
  "product_id": 2
}
</code>```

In product-index, media type

```<code>{
  "_type": "media",
  "id": 1,
  "name" : "media 1",
  "product_id": 1
}
</code>```

Now I want to query ElasticSearch to get all products along with their SKUs, medias as well.

Expected response:

```<code>[
 {
   "_type": "product",
   "id": 1,
   "name" : "product 1",
   "skus" : [
       {
         "_type": "sku",
         "id": 1,
         "name" : "sku 1",
         "product_id": 1
       },
       {
         "_type": "sku",
         "id": 2,
         "name" : "sku 2",
         "product_id": 1
       }
   ],
   media: [
     {
       "_type": "media",
       "id": 1,
       "name" : "media 1",
       "product_id": 1
     }
   ]
 },
 {
    "_type": "product",
    "id": 2,
    "name" : "product 2",
    "skus": [
        {
          "_type": "sku",
          "id": 3,
          "name" : "sku 3",
          "product_id": 2
        }
    ]
 }
]
</code>```

I am going through all over their documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html but couldn't find any approach.

Any thoughts on how to do it?

Just FYI, I am using java client to talk to elasticsearch.

答:
There is _parent meta field for mapping feature to create a parent/child relation. And I implemented an example for you:

```<code>DELETE 44368941

PUT 44368941
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      }
    },
    "sku": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      },
      "_parent": { "type": "product" }
    },
    "media": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      },
      "_parent": { "type": "product" }
    }
  }
}

POST 44368941/product/1
{
  "id": 1,
  "name" : "product 1"
}

POST 44368941/product/2
{
  "id": 2,
  "name" : "product 2"
}

POST 44368941/sku/1?parent=1
{
  "id": 1,
  "name" : "sku 1"
}

POST 44368941/sku/2?parent=1
{
  "id": 2,
  "name" : "sku 2"
}

POST 44368941/sku/3?parent=2
{
  "id": 3,
  "name" : "sku 3"
}

POST 44368941/media/1?parent=1
{
  "id": 1,
  "name" : "media 1"
}

POST 44368941/media/2?parent=1
{
  "id": 2,
  "name" : "media 2"
}

POST 44368941/product/_search
{
    "query" : {
        "bool": {
          "should": [
            {
              "has_child" : {
                  "type" : "sku",
                  "query" : {
                      "match_all": {}
                  },
                  "inner_hits" : {}
              }
            },
            {
              "has_child" : {
                  "type" : "media",
                  "query" : {
                      "match_all": {}
                  },
                  "inner_hits" : {}
              }
            }
          ]
        }
    }
}
</code>```

And the result is below. This is not the same your request but very similar.

```<code>{
  "took": 10,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 2,
    "hits": [
      {
        "_index": "44368941",
        "_type": "product",
        "_id": "1",
        "_score": 2,
        "_source": {
          "id": 1,
          "name": "product 1"
        },
        "inner_hits": {
          "media": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_type": "media",
                  "_id": "1",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 1,
                    "name": "media 1"
                  }
                },
                {
                  "_type": "media",
                  "_id": "2",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 2,
                    "name": "media 2"
                  }
                }
              ]
            }
          },
          "sku": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_type": "sku",
                  "_id": "1",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 1,
                    "name": "sku 1"
                  }
                },
                {
                  "_type": "sku",
                  "_id": "2",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 2,
                    "name": "sku 2"
                  }
                }
              ]
            }
          }
        }
      },
      {
        "_index": "44368941",
        "_type": "product",
        "_id": "2",
        "_score": 1,
        "_source": {
          "id": 2,
          "name": "product 2"
        },
        "inner_hits": {
          "media": {
            "hits": {
              "total": 0,
              "max_score": null,
              "hits": []
            }
          },
          "sku": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_type": "sku",
                  "_id": "3",
                  "_score": 1,
                  "_routing": "2",
                  "_parent": "2",
                  "_source": {
                    "id": 3,
                    "name": "sku 3"
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}
</code>```

For more information please check the following links:

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-parent-field.html
htt

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-inner-hits.html

https://www.elastic.co/guide/en/elasticsearch/guide/current/parent-child.html

Body:
Suppose I have one index (product-index) and multiple types (product, sku, media etc) in that index.

Example documents:

In product-index, product type

{
  "_type": "product",
  "id": 1,
  "name" : "product 1"
}

{
  "_type": "product",
  "id": 2,
  "name" : "product 2"
}

In product-index, sku type

{
  "_type": "sku",
  "id": 1,
  "name" : "sku 1",
  "product_id": 1
}
{
  "_type": "sku",
  "id": 2,
  "name" : "sku 2",
  "product_id": 1
}

{
  "_type": "sku",
  "id": 3,
  "name" : "sku 3",
  "product_id": 2
}

In product-index, media type

{
  "_type": "media",
  "id": 1,
  "name" : "media 1",
  "product_id": 1
}

Now I want to query ElasticSearch to get all products along with their SKUs, medias as well.

Expected response:

[
 {
   "_type": "product",
   "id": 1,
   "name" : "product 1",
   "skus" : [
       {
         "_type": "sku",
         "id": 1,
         "name" : "sku 1",
         "product_id": 1
       },
       {
         "_type": "sku",
         "id": 2,
         "name" : "sku 2",
         "product_id": 1
       }
   ],
   media: [
     {
       "_type": "media",
       "id": 1,
       "name" : "media 1",
       "product_id": 1
     }
   ]
 },
 {
    "_type": "product",
    "id": 2,
    "name" : "product 2",
    "skus": [
        {
          "_type": "sku",
          "id": 3,
          "name" : "sku 3",
          "product_id": 2
        }
    ]
 }
]

I am going through all over their documentation https://www.elastic.co/guide/en/elasticsearch/reference/current/search.html but couldn't find any approach.

Any thoughts on how to do it?

Just FYI, I am using java client to talk to elasticsearch.

Body:
There is _parent meta field for mapping feature to create a parent/child relation. And I implemented an example for you:

DELETE 44368941

PUT 44368941
{
  "mappings": {
    "product": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      }
    },
    "sku": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      },
      "_parent": { "type": "product" }
    },
    "media": {
      "properties": {
        "id": { "type": "integer" },
        "name": { "type": "keyword"}
      },
      "_parent": { "type": "product" }
    }
  }
}

POST 44368941/product/1
{
  "id": 1,
  "name" : "product 1"
}

POST 44368941/product/2
{
  "id": 2,
  "name" : "product 2"
}

POST 44368941/sku/1?parent=1
{
  "id": 1,
  "name" : "sku 1"
}

POST 44368941/sku/2?parent=1
{
  "id": 2,
  "name" : "sku 2"
}

POST 44368941/sku/3?parent=2
{
  "id": 3,
  "name" : "sku 3"
}

POST 44368941/media/1?parent=1
{
  "id": 1,
  "name" : "media 1"
}

POST 44368941/media/2?parent=1
{
  "id": 2,
  "name" : "media 2"
}

POST 44368941/product/_search
{
    "query" : {
        "bool": {
          "should": [
            {
              "has_child" : {
                  "type" : "sku",
                  "query" : {
                      "match_all": {}
                  },
                  "inner_hits" : {}
              }
            },
            {
              "has_child" : {
                  "type" : "media",
                  "query" : {
                      "match_all": {}
                  },
                  "inner_hits" : {}
              }
            }
          ]
        }
    }
}

And the result is below. This is not the same your request but very similar.

{
  "took": 10,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 2,
    "hits": [
      {
        "_index": "44368941",
        "_type": "product",
        "_id": "1",
        "_score": 2,
        "_source": {
          "id": 1,
          "name": "product 1"
        },
        "inner_hits": {
          "media": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_type": "media",
                  "_id": "1",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 1,
                    "name": "media 1"
                  }
                },
                {
                  "_type": "media",
                  "_id": "2",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 2,
                    "name": "media 2"
                  }
                }
              ]
            }
          },
          "sku": {
            "hits": {
              "total": 2,
              "max_score": 1,
              "hits": [
                {
                  "_type": "sku",
                  "_id": "1",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 1,
                    "name": "sku 1"
                  }
                },
                {
                  "_type": "sku",
                  "_id": "2",
                  "_score": 1,
                  "_routing": "1",
                  "_parent": "1",
                  "_source": {
                    "id": 2,
                    "name": "sku 2"
                  }
                }
              ]
            }
          }
        }
      },
      {
        "_index": "44368941",
        "_type": "product",
        "_id": "2",
        "_score": 1,
        "_source": {
          "id": 2,
          "name": "product 2"
        },
        "inner_hits": {
          "media": {
            "hits": {
              "total": 0,
              "max_score": null,
              "hits": []
            }
          },
          "sku": {
            "hits": {
              "total": 1,
              "max_score": 1,
              "hits": [
                {
                  "_type": "sku",
                  "_id": "3",
                  "_score": 1,
                  "_routing": "2",
                  "_parent": "2",
                  "_source": {
                    "id": 3,
                    "name": "sku 3"
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

For more information please check the following links:

https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-parent-field.html
htt

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-inner-hits.html

https://www.elastic.co/guide/en/elasticsearch/guide/current/parent-child.html


问:
How to create Summary and Aggregate reports from a .jtl file?
I am running a JMeter Performance test in non-GUI mode. I get the results in .jtl file. Is there a quick and easy way to produce Summary and Aggregate reports from this file?</p>

答:
If you're using jmeter 3.2, here are the following steps.

Open the JMeter GUI

Right click on Test Plan, Go to Add, then Listener and then click on Aggregate Report.

Where it say's Filename, either input the path of where your jtl file is located or click browse & find it.

Click the Save Table Data button below


问:
How to get Log file location in android device?
I need android log file in a file format. But i don't Know where is the location of log file. i go through techniques like "adb logcat". but i need the file format of error log. please help me to get the Android Log File. Iam new to this environment please help me.</p>

答:
If you want on PC then what you can do is:-

1) Go to your SDK location >platform-tools

2) Open cmd and type adb logcat >log.txt and press enter
It will generate new file log.txt there itself.

If you want to get logs on device you can try this tool


问:
Why does my serverless Lambda function reject Cache-Control header?
I'm using FineUploader to upload files to S3. While utilizing the DELETE functionality I get the following error:

XMLHttpRequest cannot load
  https://xxxxxxx.execute-api.us-east-1.amazonaws.com/prod/deleteS3File?.
  Request header field Cache-Control is not allowed by
  Access-Control-Allow-Headers in preflight response.

The lambda function was created using the awesome Serverless Framework with the following configuration:

```<code>functions:
  deleteS3File:
    handler: handler.deleteS3File
    events:
      - http:
          path: deleteS3File
          method: POST
          integration: lambda
          cors: true
          response:
            headers:
              Access-Control-Allow-Origin: "*"
</code>```

Any idea what this error means for a Lambda function and how to tackle it?

答:
The POST verb preflights an OPTIONS verb that you don't support.

So, you need to create a method for OPTIONS that will return status code 200 (success) and with the expected headers.

For both the OPTIONS and POST, try the following headers:

```<code>Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "GET, HEAD, OPTIONS, POST, PUT, DELETE"
Access-Control-Allow-Headers: "Access-Control-Allow-Headers, Cache-Control, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"
</code>```

you may fine tune the headers later to allow just what you need

Body:
I'm using FineUploader to upload files to S3. While utilizing the DELETE functionality I get the following error:

XMLHttpRequest cannot load
  https://xxxxxxx.execute-api.us-east-1.amazonaws.com/prod/deleteS3File?.
  Request header field Cache-Control is not allowed by
  Access-Control-Allow-Headers in preflight response.

The lambda function was created using the awesome Serverless Framework with the following configuration:

functions:
  deleteS3File:
    handler: handler.deleteS3File
    events:
      - http:
          path: deleteS3File
          method: POST
          integration: lambda
          cors: true
          response:
            headers:
              Access-Control-Allow-Origin: "*"

Any idea what this error means for a Lambda function and how to tackle it?

Body:
The POST verb preflights an OPTIONS verb that you don't support.

So, you need to create a method for OPTIONS that will return status code 200 (success) and with the expected headers.

For both the OPTIONS and POST, try the following headers:

Access-Control-Allow-Origin: "*"
Access-Control-Allow-Methods: "GET, HEAD, OPTIONS, POST, PUT, DELETE"
Access-Control-Allow-Headers: "Access-Control-Allow-Headers, Cache-Control, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers"

you may fine tune the headers later to allow just what you need


问:
What Standard Calls are Actually Macros
I asked a question here about assert which is implemented in the standard as a macro, not a function.

This had caused me an issue because the way that assert appears to be a function in the way it takes a parameter: assert(true) Thus I tried to use it as: std::assert(true) and of course being a macro that didn't work.

My question is this: Are there any other macros provided by the standard library which would appear as functions that take parameters?

答:
If we look at [headers] paragraphs 5 and 6 we have

Names which are defined as macros in C shall be defined as macros in the C++ standard library, even if C grants license for implementation as functions. [ Note: The names defined as macros in C include the following: assert, offsetof, setjmp, va_arg, va_end, and va_start. —end note ]

Names that are defined as functions in C shall be defined as functions in the C++ standard library.

So, if it is defined as a macro in C, it will be a macro in C++.  There are a couple of exceptions though.  from [support.runtime] paragraphs 7 and 8

The header <cstdalign> and the header <stdalign.h> shall not define a macro named alignas.

The header <cstdbool> and the header <stdbool.h> shall not define macros named bool, true, or false.

Although that those exceptions are covered by [headers]/7 as well

Identifiers that are keywords or operators in C++ shall not be defined as macros in C++ standard library headers.

There is also an exception that all classification macros defined in 7.12.3 Classification macros be overloaded by functions per [c.math]/10

The classification/comparison functions behave the same as the C macros with the corresponding names defined in 7.12.3, Classification macros, and 7.12.14, Comparison macros in the C Standard. Each function is overloaded for the three floating-point types, as follows:

```<code>int fpclassify(float x);
bool isfinite(float x);
bool isinf(float x);
bool isnan(float x);
bool isnormal(float x);
bool signbit(float x);
bool isgreater(float x, float y);
bool isgreaterequal(float x, float y);
bool isless(float x, float y);
bool islessequal(float x, float y);
bool islessgreater(float x, float y);
bool isunordered(float x, float y);
int fpclassify(double x);
bool isfinite(double x);
bool isinf(double x);
bool isnan(double x);
bool isnormal(double x);
bool signbit(double x);
bool isgreater(double x, double y);
bool isgreaterequal(double x, double y);
bool isless(double x, double y);
bool islessequal(double x, double y);
bool islessgreater(double x, double y);
bool isunordered(double x, double y);
int fpclassify(long double x);
bool isfinite(long double x);
bool isinf(long double x);
bool isnan(long double x);
bool isnormal(long double x);
bool signbit(long double x);
bool isgreater(long double x, long double y);
bool isgreaterequal(long double x, long double y);
bool isless(long double x, long double y);
bool islessequal(long double x, long double y);
bool islessgreater(long double x, long double y);
bool isunordered(long double x, long double y);
</code>```

Title: What Standard Calls are Actually Macros

Body:
If we look at [headers] paragraphs 5 and 6 we have

Names which are defined as macros in C shall be defined as macros in the C++ standard library, even if C grants license for implementation as functions. [ Note: The names defined as macros in C include the following: assert, offsetof, setjmp, va_arg, va_end, and va_start. —end note ]

Names that are defined as functions in C shall be defined as functions in the C++ standard library.

So, if it is defined as a macro in C, it will be a macro in C++.  There are a couple of exceptions though.  from [support.runtime] paragraphs 7 and 8

The header <cstdalign> and the header <stdalign.h> shall not define a macro named alignas.

The header <cstdbool> and the header <stdbool.h> shall not define macros named bool, true, or false.

Although that those exceptions are covered by [headers]/7 as well

Identifiers that are keywords or operators in C++ shall not be defined as macros in C++ standard library headers.

There is also an exception that all classification macros defined in 7.12.3 Classification macros be overloaded by functions per [c.math]/10

The classification/comparison functions behave the same as the C macros with the corresponding names defined in 7.12.3, Classification macros, and 7.12.14, Comparison macros in the C Standard. Each function is overloaded for the three floating-point types, as follows:

int fpclassify(float x);
bool isfinite(float x);
bool isinf(float x);
bool isnan(float x);
bool isnormal(float x);
bool signbit(float x);
bool isgreater(float x, float y);
bool isgreaterequal(float x, float y);
bool isless(float x, float y);
bool islessequal(float x, float y);
bool islessgreater(float x, float y);
bool isunordered(float x, float y);
int fpclassify(double x);
bool isfinite(double x);
bool isinf(double x);
bool isnan(double x);
bool isnormal(double x);
bool signbit(double x);
bool isgreater(double x, double y);
bool isgreaterequal(double x, double y);
bool isless(double x, double y);
bool islessequal(double x, double y);
bool islessgreater(double x, double y);
bool isunordered(double x, double y);
int fpclassify(long double x);
bool isfinite(long double x);
bool isinf(long double x);
bool isnan(long double x);
bool isnormal(long double x);
bool signbit(long double x);
bool isgreater(long double x, long double y);
bool isgreaterequal(long double x, long double y);
bool isless(long double x, long double y);
bool islessequal(long double x, long double y);
bool islessgreater(long double x, long double y);
bool isunordered(long double x, long double y);


问:
Listen to keypress with asyncio
Can somebody provide a sample of code which listen to keypress in nonblocking manner with asynio and put the keycode in console on every click?

It's not a question about some graphical toolkit

答:
An alternative to using queues would be to make the command line an asyn generator, and process the commands as they come in, like so:</p>

```<code>import asyncio
import sys

class UserInterface(object):

def __init__(self, task, loop):
    self.task = task
    self.loop = loop

    def get_ui(self):
        return asyncio.ensure_future(self._ui_task())

    async def _ui_cmd(self):
        while True:
            cmd = sys.stdin.readline()
            cmd = cmd.strip()
            if cmd == 'exit':
                self.loop.stop()
                return
            yield cmd

    async def _ui_task(self):
        async for cmd in self._ui_cmd():
            if cmd == 'stop_t':
                self.task.stop()
            elif cmd == 'start_t':
                self.task.start()
</code>```

Title: Listen to keypress with asyncio

Body:
An alternative to using queues would be to make the command line an asyn generator, and process the commands as they come in, like so:

import asyncio
import sys

class UserInterface(object):

def __init__(self, task, loop):
    self.task = task
    self.loop = loop

    def get_ui(self):
        return asyncio.ensure_future(self._ui_task())

    async def _ui_cmd(self):
        while True:
            cmd = sys.stdin.readline()
            cmd = cmd.strip()
            if cmd == 'exit':
                self.loop.stop()
                return
            yield cmd

    async def _ui_task(self):
        async for cmd in self._ui_cmd():
            if cmd == 'stop_t':
                self.task.stop()
            elif cmd == 'start_t':
                self.task.start()


问:
Laravel's Authentication
I have an account called users. When a user logs in they view information specific to them. When another user logs in they view the other users information. What do I need to do to ensure logged in users only view their information only?</p>

答: You can use $user = $request->user(); to get the user and return it as a variable with the view for the profile page. Then you can use the user variable to get the rest of the user's data.</p>

Title: Laravel's Authentication


问:
Parameters CrossBand Like XRCrossBandBox
I have a parameter Like the pictures Below :

How to Pull The XRLabel(Parameters) From GroupHeader1 to GroupFooter1 Like XRCrossbandBox did ?

答: unfortunately there is no such built in functionality</p>


问:
hibernate validator LengthValidator of truncated string
Is there a similar annotation to @Length in hibernate validator but it restricted on a trimmed string.

For example:

I have

```<code>@Length(max= 2);
String str;
</code>```

when:
str = " ab";

--> it will pass ok.

Thanks,

答:
As fare i know, there isn't one.

But you can easely implement your own.

The other (not so good) way is to add a getter which trim the string.

```<code>@Length(max= 2);
String getTrimmedStr() {
   return this.str.trim();
}
</code>```

But i think implementing your own Validator is the much cleaner approach.

Body:
Is there a similar annotation to @Length in hibernate validator but it restricted on a trimmed string.

For example:

I have

@Length(max= 2);
String str;

when:
str = " ab";

--> it will pass ok.

Thanks,

Body:
As fare i know, there isn't one.

But you can easely implement your own.

The other (not so good) way is to add a getter which trim the string.

@Length(max= 2);
String getTrimmedStr() {
   return this.str.trim();
}

But i think implementing your own Validator is the much cleaner approach.


问:
SubString from existing string iOS
I have two strings as followed:

```<code>NSString *newStr = @"143.2a";
NSString *expression = @"^([0-9]*)(\\.([0-9]{0,10})?)?$";
</code>```

I want to substring "newStr" such as all my characters in "expression" should be present after subString. Like

```<code>NSString * extractedString = @"143.2";
</code>```

(except all alphabets and symbols other than single'.')

How shall I do this?

答:
First of all, your regex pattern won't extract that string.

If you want to check for one or more digits followed be a dot followed be one or more digits the pattern is supposed to be

```<code>NSString *expression = @"\\d+\\.\\d+";
</code>```

To extract the string use the NSRegularExpression class as suggested by Larme.

```<code>NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:0 error:nil];
NSTextCheckingResult *firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, newStr.length)];
if (firstMatch) {
    NSString *extractedString = [newStr substringWithRange:firstMatch.range];
    NSLog(@"%@", extractedString);
} else {
    NSLog(@"Not Found");
}
</code>```

Title: SubString from existing string iOS

Body:
I have two strings as followed:

NSString *newStr = @"143.2a";
NSString *expression = @"^([0-9]*)(\\.([0-9]{0,10})?)?$";

I want to substring "newStr" such as all my characters in "expression" should be present after subString. Like

NSString * extractedString = @"143.2";

(except all alphabets and symbols other than single'.')

How shall I do this?

Body:
First of all, your regex pattern won't extract that string.

If you want to check for one or more digits followed be a dot followed be one or more digits the pattern is supposed to be

NSString *expression = @"\\d+\\.\\d+";

To extract the string use the NSRegularExpression class as suggested by Larme.

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:0 error:nil];
NSTextCheckingResult *firstMatch = [regex firstMatchInString:newStr options:0 range:NSMakeRange(0, newStr.length)];
if (firstMatch) {
    NSString *extractedString = [newStr substringWithRange:firstMatch.range];
    NSLog(@"%@", extractedString);
} else {
    NSLog(@"Not Found");
}


问:
I want to download and upload a pdf after creating it from html using javascript
HERE is the code i used to download the file.

I want to upload the same file to server.

The file was created from html.

```<code>$scope.callPdf = function (studentId) {
    html2canvas(document.getElementById('download'), {
        onrendered: function (canvas) {
            var data = canvas.toDataURL();
            var docDefinition = { content: [{ image: data, width: 450 }] };
            pdfMake.createPdf(docDefinition).download(studentId + ".pdf");
        }
    });

}`
</code>```

答:
You can use getDataURL method and receive store it in variable and then use it for upload.</p>

```<code>pdfMake.createPdf(docDefinition).getDataUrl(function(dataUrl){
var pdfFile = dataUrl;
//upload code goes here
});
</code>```

Body:
HERE is the code i used to download the file.

I want to upload the same file to server.

The file was created from html.

$scope.callPdf = function (studentId) {
    html2canvas(document.getElementById('download'), {
        onrendered: function (canvas) {
            var data = canvas.toDataURL();
            var docDefinition = { content: [{ image: data, width: 450 }] };
            pdfMake.createPdf(docDefinition).download(studentId + ".pdf");
        }
    });

}`

Body:
You can use getDataURL method and receive store it in variable and then use it for upload.

pdfMake.createPdf(docDefinition).getDataUrl(function(dataUrl){
var pdfFile = dataUrl;
//upload code goes here
});


问:
Multiple Google Recaptchas in a same page
I have a problem here, I included 2 recaptchas on my page and they are working properly, however at the time of cleaning them (after giving the submit by ajax) I can not reset the recaptcha, if I use the "grecaptcha.reset" it wipes only one recaptcha ..
Thanks!</p>

答:
Here is my simple solution, this way u can prepare as many captchas as u need on the same page. Remember to put google api elements: SiteKey and SecretKey!

Back-end:

```<code><?php

$siteKey = 'Paste element provided by google api';
$secretKey = 'Paste element provided by google api';

if($_POST['submit']){

    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
}?>
</code>```

And the front-end:

```<code><html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <h3>First form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha1"></div>
        <input type="submit" name="submit" value="send"/>
    </form>

    <h3>Second form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha2"></div>
        <input type="submit" name="submit" value="send"/>
    </form>

    <script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
    <script>
        var recaptcha1;
        var recaptcha2;
        var myCallBack = function() {

            recaptcha1 = grecaptcha.render('recaptcha1', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'light'
            });

            recaptcha2 = grecaptcha.render('recaptcha2', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'dark'
            });
        };
    </script>
</body>
</code>```

Cheers!

Body:
Here is my simple solution, this way u can prepare as many captchas as u need on the same page. Remember to put google api elements: SiteKey and SecretKey!

Back-end:

<?php

$siteKey = 'Paste element provided by google api';
$secretKey = 'Paste element provided by google api';

if($_POST['submit']){

    $username = $_POST['username'];
    $responseKey = $_POST['g-recaptcha-response'];
    $userIP = $_SERVER['REMOTE_ADDR'];
    $url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey&remoteip=$userIP";
    $response = file_get_contents($url);
    $response = json_decode($response);
    if($response->success){
        echo "Verification is correct. Your name is $username";
    } else {
        echo "Verification failed";
    }
}?>

And the front-end:

<html>
<meta>
    <title>Google ReCaptcha</title>
</meta>
<body>
    <h3>First form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha1"></div>
        <input type="submit" name="submit" value="send"/>
    </form>

    <h3>Second form</h3>
    <form action="index.php" method="post">
        <input type="text" name="username" placeholder="Write your name"/>
        <div id="recaptcha2"></div>
        <input type="submit" name="submit" value="send"/>
    </form>

    <script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
    <script>
        var recaptcha1;
        var recaptcha2;
        var myCallBack = function() {

            recaptcha1 = grecaptcha.render('recaptcha1', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'light'
            });

            recaptcha2 = grecaptcha.render('recaptcha2', {
                'sitekey' : '<?= $siteKey ?>',
                'theme' : 'dark'
            });
        };
    </script>
</body>

Cheers!


问:
ActionScript 3 / MXML : My code doesn't do anything
Compiling my code into a SWF file results in a program that does nothing. I expected a solid rectangle with color #FFAA00. Why is my code not doing anything?

dummy.as:

```<code>//Dependencies
import flash.display.*;
import flash.events.*;

//Variables
var GlobalTimer:int = 0;
var Rect:Shape = new Shape();

//Game loader function
public function handle():void
{
    init();
}

//Init function
public function init():void
{
    addChild(Rect);
    addEventListener(Event.ENTER_FRAME,loop);
}

//Loop function
public function loop(event:Event):void
{
    var CurTimer:int = getTimer();
    var FrameDiff:int = CurTimer-GlobalTimer;
    GlobalTimer = CurTimer;

    Rect.graphics.beginFill(0xFFAA00);
    Rect.graphics.drawRect(0,0,640,480);
    Rect.graphics.endFill();
}
</code>```

dummy.mxml:

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Application width="640" height="480" xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="handle()">
    <mx:Script source="dummy.as"/>
</mx:Application>
</code>```

Compiled using:

```<code>./mxmlc ../../feedsparky/src/dummy/dummy.mxml
</code>```

答:
Because Shape does not meet the conditions as a child. Read carefully:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Container.html#addChild()

In order to add basic Flash display classes to Flex display list you need to have UIComponent as their parent. You can see the chain of inheritance here:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Application.html

```<code>var FlashBox:UIComponent = new UIComponent;
var Rect:Shape = new Shape;

//Init function
public function init():void
{
    addChild(FlashBox);
    FlashBox.addChild(Rect);

    addEventListener(Event.ENTER_FRAME, loop);
}
</code>```

Body:
Compiling my code into a SWF file results in a program that does nothing. I expected a solid rectangle with color #FFAA00. Why is my code not doing anything?

dummy.as:

//Dependencies
import flash.display.*;
import flash.events.*;

//Variables
var GlobalTimer:int = 0;
var Rect:Shape = new Shape();

//Game loader function
public function handle():void
{
    init();
}

//Init function
public function init():void
{
    addChild(Rect);
    addEventListener(Event.ENTER_FRAME,loop);
}

//Loop function
public function loop(event:Event):void
{
    var CurTimer:int = getTimer();
    var FrameDiff:int = CurTimer-GlobalTimer;
    GlobalTimer = CurTimer;

    Rect.graphics.beginFill(0xFFAA00);
    Rect.graphics.drawRect(0,0,640,480);
    Rect.graphics.endFill();
}

dummy.mxml:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application width="640" height="480" xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="handle()">
    <mx:Script source="dummy.as"/>
</mx:Application>

Compiled using:

./mxmlc ../../feedsparky/src/dummy/dummy.mxml

Body:
Because Shape does not meet the conditions as a child. Read carefully:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Container.html#addChild()

In order to add basic Flash display classes to Flex display list you need to have UIComponent as their parent. You can see the chain of inheritance here:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/core/Application.html

var FlashBox:UIComponent = new UIComponent;
var Rect:Shape = new Shape;

//Init function
public function init():void
{
    addChild(FlashBox);
    FlashBox.addChild(Rect);

    addEventListener(Event.ENTER_FRAME, loop);
}


问:
Find text before phone number in string regex PHP
So I have this list of strings given to me as follows:

```<code>David palmer & Betsy Harrell 229-548-9651 Emily
</code>```

I know how to get the phone number out of that string by doing this:

```<code>preg_match_all('/[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];
</code>```

But I need to get the name before hand AND the phone number. This is a bit beyond my regex knowledge. So I need

```<code>David palmer & Betsy Harrell
</code>```

and

```<code>229-548-9651
</code>```

答:
Use capturing groups to get two substrings:

```<code>$s = 'David palmer & Betsy Harrell 229-548-9651 Emily';
if (preg_match('~^(.*?)\s*(\d{3}-\d{3}-\d{4})~', $s, $m)) {
  echo $m[1] . "\n" . $m[2];
}
</code>```

See PHP demo.

Pattern details:

^ - start of string

(.*?) - any 0+ chars other than line break chars as few as possible up to the first...

\s* - 0+ whitespaces

(\d{3}-\d{3}-\d{4}) - date pattern (3 digits, -, 3 digits, -, 4 digits).

Note you do not need to put - into a character class, and no need to escape it outside a character class. \d is equal to [0-9] if you do not use any specific modifiers/PCRE verbs related to Unicode.

Body:
So I have this list of strings given to me as follows:

David palmer & Betsy Harrell 229-548-9651 Emily

I know how to get the phone number out of that string by doing this:

preg_match_all('/[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];

But I need to get the name before hand AND the phone number. This is a bit beyond my regex knowledge. So I need

David palmer & Betsy Harrell

and

229-548-9651

Body:
Use capturing groups to get two substrings:

$s = 'David palmer & Betsy Harrell 229-548-9651 Emily';
if (preg_match('~^(.*?)\s*(\d{3}-\d{3}-\d{4})~', $s, $m)) {
  echo $m[1] . "\n" . $m[2];
}

See PHP demo.

Pattern details:

^ - start of string

(.*?) - any 0+ chars other than line break chars as few as possible up to the first...

\s* - 0+ whitespaces

(\d{3}-\d{3}-\d{4}) - date pattern (3 digits, -, 3 digits, -, 4 digits).

Note you do not need to put - into a character class, and no need to escape it outside a character class. \d is equal to [0-9] if you do not use any specific modifiers/PCRE verbs related to Unicode.


问:
Using batch size with TensorFlow Validation Monitor
I'm using tf.contrib.learn.Estimator to train a CNN having 20+ layers. I'm using GTX 1080 (8 GB) for training. My dataset is not so large but my GPU runs out of memory with a batch size greater than 32. So I'm using a batch size of 16 for training and Evaluating the classifier (GPU runs out of memory while evaluation as well if a batch_size is not specified).

```<code>  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = classifier.evaluate(
      x=X_test, y=y_test, metrics=metrics, batch_size=16)
</code>```

Now the problem is that after every 100 steps, I only get training loss printed on screen. I want to print validation loss and accuracy as well, So I'm using a ValidationMonitor

```<code> validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
      X_test,
      y_test,
      every_n_steps=50)
  # Train the model
  classifier.fit(
      x=X_train,
      y=y_train,
      batch_size=8,
      steps=20000,
      monitors=[validation_monitor]
</code>```

ActualProblem: My code crashes (Out of Memory) when I use ValidationMonitor, I think the problem might be solved if I could specify a batch size here as well and I can't figure out how to do that. I want ValidationMonitor to evaluate my validation data in batches, like I do it manually after training using classifier.evaluate, is there a way to do that?

答: The ValidationMonitor's constructor accepts a batch_size arg that should do the trick.

Body:
I'm using tf.contrib.learn.Estimator to train a CNN having 20+ layers. I'm using GTX 1080 (8 GB) for training. My dataset is not so large but my GPU runs out of memory with a batch size greater than 32. So I'm using a batch size of 16 for training and Evaluating the classifier (GPU runs out of memory while evaluation as well if a batch_size is not specified).

  # Configure the accuracy metric for evaluation
  metrics = {
      "accuracy":
          learn.MetricSpec(
              metric_fn=tf.metrics.accuracy, prediction_key="classes"),
  }

  # Evaluate the model and print results
  eval_results = classifier.evaluate(
      x=X_test, y=y_test, metrics=metrics, batch_size=16)

Now the problem is that after every 100 steps, I only get training loss printed on screen. I want to print validation loss and accuracy as well, So I'm using a ValidationMonitor

 validation_monitor = tf.contrib.learn.monitors.ValidationMonitor(
      X_test,
      y_test,
      every_n_steps=50)
  # Train the model
  classifier.fit(
      x=X_train,
      y=y_train,
      batch_size=8,
      steps=20000,
      monitors=[validation_monitor]

ActualProblem: My code crashes (Out of Memory) when I use ValidationMonitor, I think the problem might be solved if I could specify a batch size here as well and I can't figure out how to do that. I want ValidationMonitor to evaluate my validation data in batches, like I do it manually after training using classifier.evaluate, is there a way to do that?


问:
Return type of array access operator overload
I have a class Foo that manages a collection of objects of another class Bar. The managing class has a method Bar *Foo::at( int index ) to access the objects int he collection, so I can do something like myfoo->at(2)->barmethod(), say. Now I was wondering if I can overload Foo::operator[] to return a Bar*, so I could do myfoo[2]->barmethod() instead. The compiler doesn't like that. Does the return type of the operator necessarily need to be a reference to the class it is a member of?

Here is some code. The first works, the second doesn't.

```<code>Foo::Bar *Foo::at( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

Foo::Bar *Foo::operator[]( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}
</code>```

From the header:

```<code>class Foo
{
public:

    class Bar
    {
    ...
    };

    size_t add( UINT8 addr, UINT8 type, UINT8 opt, UINT8 rev );
    Bar    *at( size_t index );
    Bar    *operator[]( size_t index );
    ....

protected:

    Bar             **m_entry;      // array of entry pointers
    size_t          m_size;
    size_t          m_count;

};
</code>```

Here's the code the compiler doesn't like (when using [ ]):

```<code>Foo *myfoo;
...
myfoo[i]->barmethod();
</code>```

and now in writing this I see what the problem is. I'm using [] on a POINTER to a Foo, not on an actual Foo. So if I dereference it, it should work. The compiler error is exactly right:

error: base operand of '->' has non-pointer type 'Foo'

Duh. Okay, sorry for the dumb question. Thanks for your suggestions.

答:
No. The only thing you can't change when overloading operator[] is its arity: that is, you can't change the number of parameters.

But you can change the type of the parameter (although std::size_t is common), and you can change the return type too. (Although const Bar& is common for the const overload of [], and Bar& is common for the non-const overload).

Body:
I have a class Foo that manages a collection of objects of another class Bar. The managing class has a method Bar *Foo::at( int index ) to access the objects int he collection, so I can do something like myfoo->at(2)->barmethod(), say. Now I was wondering if I can overload Foo::operator[] to return a Bar*, so I could do myfoo[2]->barmethod() instead. The compiler doesn't like that. Does the return type of the operator necessarily need to be a reference to the class it is a member of?

Here is some code. The first works, the second doesn't.

Foo::Bar *Foo::at( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

Foo::Bar *Foo::operator[]( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

From the header:

class Foo
{
public:

    class Bar
    {
    ...
    };

    size_t add( UINT8 addr, UINT8 type, UINT8 opt, UINT8 rev );
    Bar    *at( size_t index );
    Bar    *operator[]( size_t index );
    ....

protected:

    Bar             **m_entry;      // array of entry pointers
    size_t          m_size;
    size_t          m_count;

};

Here's the code the compiler doesn't like (when using [ ]):

Foo *myfoo;
...
myfoo[i]->barmethod();

and now in writing this I see what the problem is. I'm using [] on a POINTER to a Foo, not on an actual Foo. So if I dereference it, it should work. The compiler error is exactly right:

error: base operand of '->' has non-pointer type 'Foo'

Duh. Okay, sorry for the dumb question. Thanks for your suggestions.


问:
make comma separated strings from multidimensional array
I have JavaScript multidimensional array like this:

```<code>a   1
b   2
c   3
</code>```

I want it converted into comma separated value like this:

```<code>function reg() {
    var result = [];
    var comma_value;

    for (var i = 0; i < arrc.length; i++) {
        if (parseInt(arrc[i].value)) {
            result.push([arrp[i].value, arrc[i].value]);
        }

        // result is an array
        // My desired result:
        // comma_value = "a,1;b,2;c,3"
    }

    $('#str').val(JSON.stringify(result));

    console.table(result);
    console.log(result.join(', '));
}
</code>```

答:
```<code>alert( [["a",1],["b",2]].map(e=>e.join()).join(";"));
</code>```

Join the inner Arrays, then the outer...

Body:
I have JavaScript multidimensional array like this:

a   1
b   2
c   3

I want it converted into comma separated value like this:

function reg() {
    var result = [];
    var comma_value;

    for (var i = 0; i < arrc.length; i++) {
        if (parseInt(arrc[i].value)) {
            result.push([arrp[i].value, arrc[i].value]);
        }

        // result is an array
        // My desired result:
        // comma_value = "a,1;b,2;c,3"
    }

    $('#str').val(JSON.stringify(result));

    console.table(result);
    console.log(result.join(', '));
}

Body:
alert( [["a",1],["b",2]].map(e=>e.join()).join(";"));

Join the inner Arrays, then the outer...


问:
heroku app web constantly firing warning run id unauthorised
I have an application deployed over heroku where I have paid for hobby dyno plan and a paid postgres instance.

My heroku pipeline is also completely set up where I have multiple apps running different versions of the application

The problem only rises in the paid app as below-

```<code>2017-06-05T11:00:24.816860+00:00 app[web.1]: 2017/06/05 11:00:24.816756
(7) Warning: app "my-app-name" with run id "21****3840926*****"
received unauthorized
</code>```

On reporting this to heroku The only reply i have recived is that it's a problem with the application. By I am wondering if it's an application error why will it appear in only one instance and not in any other environment.

Also what I am not able to understand is what exactly it means by run id

Any help for the right direction will be great.

答:
It was resolved,

The problem was with a dangling env config variable. An addon which was removed/expired still had the env config var set, making it throw the error.

The following process helped me debug the situation

Code Review

Dependencies check

Bad Data(db related)

Config Environment(.env)

Body:
I have an application deployed over heroku where I have paid for hobby dyno plan and a paid postgres instance.

My heroku pipeline is also completely set up where I have multiple apps running different versions of the application

The problem only rises in the paid app as below-

2017-06-05T11:00:24.816860+00:00 app[web.1]: 2017/06/05 11:00:24.816756
(7) Warning: app "my-app-name" with run id "21****3840926*****"
received unauthorized

On reporting this to heroku The only reply i have recived is that it's a problem with the application. By I am wondering if it's an application error why will it appear in only one instance and not in any other environment.

Also what I am not able to understand is what exactly it means by run id

Any help for the right direction will be great.