问:
Javascript contact form with contact.php file not found or internal server error
I have a contact form on my test website, but when I send the message its providing me the following error

mail/contact_me.php 404 (Not Found)

But the file is on the server. I'm using Wordpress on the website. I tried to add different things but it still not working. How can I fix this? Check the code below

I tried just to put the contactform.js on my index file and change the link with template url but its still not working :(

JS

```<code>$(function() {
    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "../../mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Thank you! We'll be in touch very soon. If you'd like to make a reservation in the meantime, please find us on Expedia. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>So sorry " + firstName + ", it seems that our mail server is not responding. Please call us while we resolve this issue. ");
                    $('#success > .alert-danger').append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});
</code>```

PHP

```<code><?php
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "No arguments Provided!";
    return false;
}

$name          = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message       = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to            = 'test@YOURDOMAIN.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body    = "You have received a new message from your website contact form.\n\n" . "Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers       = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>
</code>```

HTML

```<code><form id="contactForm" name="sentMessage" novalidate>
    <div class="row">
        <div class="col-md-6">
            <div class="form-group">
                <input class="form-control" id="name" type="text" placeholder="Your Name *" required data-validation-required-message="Please enter your name.">
                <p class="help-block text-danger"></p>
            </div>
            <div class="form-group">
                <input class="form-control" id="email" type="email" placeholder="Your Email *" required data-validation-required-message="Please enter your email address.">
                <p class="help-block text-danger"></p>
            </div>
            <div class="form-group">
                <input class="form-control" id="phone" type="tel" placeholder="Your Phone *" required data-validation-required-message="Please enter your phone number.">
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="col-md-6">
            <div class="form-group">
                <textarea class="form-control" id="message" placeholder="Your Message *" required data-validation-required-message="Please enter a message."></textarea>
                <p class="help-block text-danger"></p>
            </div>
        </div>
        <div class="clearfix"></div>
        <div class="col-lg-12 text-center">
            <div id="success"></div>
            <button id="sendMessageButton" class="btn btn-primary btn-xl text-uppercase" type="submit">Send Message</button>
        </div>
    </div>
</form>
</code>```

答:
Change your JS, and replace

```<code>url: "../../mail/contact_me.php",
</code>```

with

```<code>url: "https://example.com/complete/path/to/mail/contact_me.php",
</code>```

so that your form will be submitted to the correct place. Right now the URL of contact_me.php is relative to either your JS file or your page's URL (depending on whether the JS is inlined or not), and that's asking for trouble.

You could get away with a locally absolute uri aka

```<code>url: "/complete/path/to/mail/contact_me.php",
</code>```

But that will come back to haunt you if you ever decide to put static files like JS, CSS and images onto another host like a CDN.

Body:
I have a contact form on my test website, but when I send the message its providing me the following error

mail/contact_me.php 404 (Not Found)

But the file is on the server. I'm using Wordpress on the website. I tried to add different things but it still not working. How can I fix this? Check the code below

I tried just to put the contactform.js on my index file and change the link with template url but its still not working :(

JS

$(function() {
    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "../../mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                cache: false,
                success: function() {
                    // Success message
                    $('#success').html("
");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("Thank you! We'll be in touch very soon. If you'd like to make a reservation in the meantime, please find us on Expedia. ");
                    $('#success > .alert-success')
                        .append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
                error: function() {
                    // Fail message
                    $('#success').html("
");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
                        .append("</button>");
                    $('#success > .alert-danger').append("So sorry " + firstName + ", it seems that our mail server is not responding. Please call us while we resolve this issue. ");
                    $('#success > .alert-danger').append('
');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

PHP

<?php
// Check for empty fields
if (empty($_POST['name']) || empty($_POST['email']) || empty($_POST['phone']) || empty($_POST['message']) || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
    echo "No arguments Provided!";
    return false;
}

$name          = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$message       = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to            = 'test@YOURDOMAIN.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body    = "You have received a new message from your website contact form.\n\n" . "Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers       = "From: noreply@yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>

HTML

<form id="contactForm" name="sentMessage" novalidate>

                <input class="form-control" id="name" type="text" placeholder="Your Name *" required data-validation-required-message="Please enter your name.">

                <input class="form-control" id="email" type="email" placeholder="Your Email *" required data-validation-required-message="Please enter your email address.">

                <input class="form-control" id="phone" type="tel" placeholder="Your Phone *" required data-validation-required-message="Please enter your phone number.">

                <textarea class="form-control" id="message" placeholder="Your Message *" required data-validation-required-message="Please enter a message."></textarea>

            <button id="sendMessageButton" class="btn btn-primary btn-xl text-uppercase" type="submit">Send Message</button>

</form>

Body:
Change your JS, and replace

url: "../../mail/contact_me.php",

with

url: "https://example.com/complete/path/to/mail/contact_me.php",

so that your form will be submitted to the correct place. Right now the URL of contact_me.php is relative to either your JS file or your page's URL (depending on whether the JS is inlined or not), and that's asking for trouble.

You could get away with a locally absolute uri aka

url: "/complete/path/to/mail/contact_me.php",

But that will come back to haunt you if you ever decide to put static files like JS, CSS and images onto another host like a CDN.


来源: stackexchange

问:
Using 2 different data to show in chart laravel
I am currently using chartTV to create a chart but my chart doesn't seem to appear inside my blade for some reason, the title can be seen but not the graph. I want to create an areaspline chart where it will show number of people hired and not hired this week. I tried doing something like this but it not working. Can someone guide me in doing it correctly? How should I do it?

My dashboardController:

```<code>$user1s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('Evaluation_Status', '=', 'No')
             ->get();
$user2s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('evaluations.Evaluation_Status', '=', 'Yes')
             ->get();

Charts::Database($user1s, $user2s, 'areaspline', 'highcharts')
       ->title('My nice chart')
       ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
       ->dataset('Hired', [$user1s])
       ->dataset('Not Hired', [$user2s]);

return view('dashboard', ['chart' => $chart]);
</code>```

My dashboard.blade.php

```<code>{!! Charts::assets() !!}
{!! $chart->render() !!}
</code>```

答:
Multi database charts can be used if using data from different database tables. The APIs are similar to Charts::multi. The only differentiation is how datasets are specified.</p>

```<code>$charts = Charts::multiDatabase('areaspline', 'highcharts')
            ->title('My nice chart')
            ->colors(['#ff0000', '#ffffff'])
            ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
            ->dataset('Hired', $user1s)
            ->dataset('Not Hired', $user2s);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently using chartTV to create a chart but my chart doesn't seem to appear inside my blade for some reason, the title can be seen but not the graph. I want to create an areaspline chart where it will show number of people hired and not hired this week. I tried doing something like this but it not working. Can someone guide me in doing it correctly? How should I do it?

My dashboardController:

$user1s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('Evaluation_Status', '=', 'No')
             ->get();
$user2s = DB::table('evaluations')
             ->select('evaluations.Evaluation_Status','evaluations.created_at' )
             ->where('evaluations.Evaluation_Status', '=', 'Yes')
             ->get();

Charts::Database($user1s, $user2s, 'areaspline', 'highcharts')
       ->title('My nice chart')
       ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
       ->dataset('Hired', [$user1s])
       ->dataset('Not Hired', [$user2s]);

return view('dashboard', ['chart' => $chart]);

My dashboard.blade.php

{!! Charts::assets() !!}
{!! $chart->render() !!}

Body:
Multi database charts can be used if using data from different database tables. The APIs are similar to Charts::multi. The only differentiation is how datasets are specified.

$charts = Charts::multiDatabase('areaspline', 'highcharts')
            ->title('My nice chart')
            ->colors(['#ff0000', '#ffffff'])
            ->labels(['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday','Saturday', 'Sunday'])
            ->dataset('Hired', $user1s)
            ->dataset('Not Hired', $user2s);


问:
Change font family of object using its id
I need to change my font family of specific object using its id

Any suggestions how I do it?

```<code><script>
    var day = new Date();
    var today = day.getDate();
    var lys = today * 16;
    var heode = 505 - lys;

    if (today == 24){
    document.getElementById("chistmas").innerHTML ="Merry Christmas"
    }
    else {
        let remainingdays = 24 - today;
        document.getElementById("chistmas").innerHTML = "there are " + remainingdays + " days until christmas"
    }
    document.getElementsByClassName("light")[0].style.height=heode+"px"
</script>
</code>```

答:
you can do something like below:

```<code>document.getElementById("chistmas").innerHTML ="<label style='font-family:Arial, Helvetica, sans-serif'>Merry Christmas</label>"
</code>```

or,

```<code>label.yourClassName {
    font-family: "Times New Roman", Times, serif;
}

document.getElementById("chistmas").innerHTML ="<label class='yourClassName'>Merry Christmas</label>"
</code>```

Body:
you can do something like below:

document.getElementById("chistmas").innerHTML ="<label style='font-family:Arial, Helvetica, sans-serif'>Merry Christmas</label>"

or,

label.yourClassName {
    font-family: "Times New Roman", Times, serif;
}

document.getElementById("chistmas").innerHTML ="<label class='yourClassName'>Merry Christmas</label>"


问:
QML Repeater and QML Grid Layout with variable number of columns
I have an model that consist of objects with some properties, e.g.:

```<code>ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}
</code>```

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

```<code>GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}
</code>```

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

```<code>GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}
</code>```

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

```<code>GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}
</code>```

UPD2:
Modified variant from @m7913d:

```<code>GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}
</code>```

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

答:
Here is yet another solution:

The Idea: add the children in the right order

For that we will need to make sure that all Items for a model entry.

```<code>GridLayout {
    id: gl
    columns: parent.width > 235 ? 3 : 1
}
Instantiator {
    model: fruitModel
    delegate: QtObject {
        property Item text: Text { parent: gl; text: model.name }
        property Item rect: Rectangle { parent: gl; color: model.color; width: 50; height: 50; }
        property Item spin: SpinBox { parent: gl; value: model.cost; }
    }
}
</code>```

Note: This will fail when entries in the model will be inserted or reordered, as in this solution the entries are always appended.

  Other than that, it will automatically support column changes

Body:
I have an model that consist of objects with some properties, e.g.:

ListModel {
    id: fruitModel

    ListElement {
        name: "Apple"
        color: "green"
        cost: 2.45
    }
    ListElement {
        name: "Orange"
        color: "orange"
        cost: 3.25
    }
    ListElement {
        name: "Banana"
        color: "yellow"
        cost: 1.95
    }
}

And now I want to display this model using GridLayout. For each property I want to use one element inside GridLayout, e.g:

GridLayout {
    columns: 3

    Text { text: "Apple" }
    Rectangle { color: "green" }
    SpinBox { value: 2.45 }

    Text { text: "Orange" }
    Rectangle { color: "orange" }
    SpinBox { value: 3.25 }

    Text { text: "Banana" }
    Rectangle { color: "yellow" }
    SpinBox { value: 1.95 }
}

The point is that I can easily change the columns property of GridLayout and make my layout narrower (e.g. to fit small screens). I can use Repeater to fill GridLayout. However such approach will fill my GridLayout in wrong order:

GridLayout {
    columns: 3

    Repeater {
        model: fruitModel
        Text { text: name }
    }

    Repeater {
        model: fruitModel
        Rectangle { color: color }
    }

    Repeater {
        model: fruitModel
        SpinBox { value: value }
    }
}

And it is waste to use Layout.column and Layout.row attached properties since I want to easily change number of columns in GridLayout.

Is there any way to fill GridLayout with data from model row by row?

UPD1:

Behaviour that I want to get:

GridLayout {
    columns: parent.width > 235 ? 3 : 1

    Text { text: "Apple" }
    Rectangle { color: "green"; width: 40; height: 40 }
    SpinBox { value: 2 }

    Text { text: "Orange" }
    Rectangle { color: "orange"; width: 40; height: 40 }
    SpinBox { value: 3 }

    Text { text: "Banana" }
    Rectangle { color: "yellow"; width: 40; height: 40 }
    SpinBox { value: 1 }
}

UPD2:
Modified variant from @m7913d:

GridLayout {
    id: layout
    property int maxColumns: 3
    columns: parent.width > 235 ? maxColumns : 1

    Repeater {
        model: fruitModel
        Text {
            text: name
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index)
            Layout.column: 0
        }
    }

    Repeater {
        model: fruitModel
        Rectangle {
            Layout.preferredWidth: 30
            Layout.preferredHeight: 30
            color: col
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 1)
            Layout.column: layout.columns == maxColumns ? 1 : 0
        }
    }

    Repeater {
        model: fruitModel
        SpinBox {
            value: val
            Layout.row: layout.columns == maxColumns ? index : (maxColumns * index + 2)
            Layout.column: layout.columns == maxColumns ? 2 : 0
        }
    }
}

It's working but not easy-to-modify solution plus sometimes during layout resize there is messages QGridLayoutEngine::addItem: Cell (1, 0) already taken.

Body:
Here is yet another solution:

The Idea: add the children in the right order

For that we will need to make sure that all Items for a model entry.

GridLayout {
    id: gl
    columns: parent.width > 235 ? 3 : 1
}
Instantiator {
    model: fruitModel
    delegate: QtObject {
        property Item text: Text { parent: gl; text: model.name }
        property Item rect: Rectangle { parent: gl; color: model.color; width: 50; height: 50; }
        property Item spin: SpinBox { parent: gl; value: model.cost; }
    }
}

Note: This will fail when entries in the model will be inserted or reordered, as in this solution the entries are always appended.

  Other than that, it will automatically support column changes


问:
Combinations with repetition of letters with weight from list
I have four letters with different weights as

```<code>letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]
</code>```

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

```<code>comb_w2 = ['CC','NN','NC','O','S']
</code>```

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.

答:
Yours is a problem of partitioning (not easy stuff).
You can use this post to generate all possible combination outcomes for a given weight. Then you can delete the ones that contain keys which you don't have in weights_of_l. Finally you substitute the numbers by the letters and create permutations for they letters that have the same weight.

Body:
I have four letters with different weights as

letters = ['C', 'N', 'O', 'S']
weights_of_l = [1, 1, 2, 2]

I want to get the combinations of letters which weight = 2. The letter can be repeatedly chose and order is not important. The result can be list or array or any forms but with this combinations

comb_w2 = ['CC','NN','NC','O','S']

Here C and N has weight = 1 so combining two letters have weight = 2: The possible combinations are 'CC','NN','NC'

O and S has weight = 2 already so it cannot combine with other letters. Is there any libraries for calculating this? I saw itertools but it gives only the number of possibility, not the combinations.


问:
Subscribing to the same observable (shared) from different components with params
I have two components on the same page. Each component is displaying stuff regarding orders subscribing to an Observable coming from a service with parameters.

The service:

```<code>getOrders(url: string, query: string) : Observable<any> {
        return this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .share();

    }
</code>```

Component 1:

```<code>    Observable.combineLatest(this.behaviorsubject1,this.behaviorsubject2)
    .subscribe((res)=>{
                this.combineLatestStream = res;
                this.selectedOrganization = this.combineLatestStream[1];

                this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id);
                this.mainService$.subscribe(result => {
                //call 1
                });

    });
</code>```

Component 2:

```<code>  this.aservice.stuff.subscribe((res) => {
    this.selectedOrganization = res;
    this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id+"&status=1");
    this.mainService$.subscribe((val) => {
       //call 2
    })
  })
</code>```

In first component I get all the orders; In the second component I get only some of them (based on some parameters); both with mainService$. I will have more components that will need to subscribe to this service. Sharing the service is not working. Any other methods?

I tried with publishReplay(1).refCount() too. I don't want to have multiple API calls.

答:
The http observable completes after subscribe, if you want that all subscriber will be notified you need to use BehaviorSubject and call on getOrders behaviorSubject.next():

Example:

```<code>behaviorSubject = new BehaviorSubject(<Orders[]>{})

getOrders(url: string, query: string) : void {
        this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .do((orders) => behaviorSubject.next(orders))
                        .subscribe();

    }
</code>```

Body:
I have two components on the same page. Each component is displaying stuff regarding orders subscribing to an Observable coming from a service with parameters.

The service:

getOrders(url: string, query: string) : Observable<any> {
        return this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .share();

    }

Component 1:

    Observable.combineLatest(this.behaviorsubject1,this.behaviorsubject2)
    .subscribe((res)=>{
                this.combineLatestStream = res;
                this.selectedOrganization = this.combineLatestStream[1];

                this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id);
                this.mainService$.subscribe(result => {
                //call 1
                });

    });

Component 2:

  this.aservice.stuff.subscribe((res) => {
    this.selectedOrganization = res;
    this.mainService$ = this.orderService.getOrders(this.settings.backend.orders, "organization_id="+this.selectedOrganization.organization_id+"&status=1");
    this.mainService$.subscribe((val) => {
       //call 2
    })
  })

In first component I get all the orders; In the second component I get only some of them (based on some parameters); both with mainService$. I will have more components that will need to subscribe to this service. Sharing the service is not working. Any other methods?

I tried with publishReplay(1).refCount() too. I don't want to have multiple API calls.

Body:
The http observable completes after subscribe, if you want that all subscriber will be notified you need to use BehaviorSubject and call on getOrders behaviorSubject.next():

Example:

behaviorSubject = new BehaviorSubject(<Orders[]>{})

getOrders(url: string, query: string) : void {
        this.http.get(url + "&" + query, this.options)
                        .map((res:Response) => res.json())
                        .catch((error:any) => Observable.throw(error || 'Server error'))
                        .do((orders) => behaviorSubject.next(orders))
                        .subscribe();

    }


问:
Is there a reusable UITableViewCell with a label and text field?
It's a common user interface pattern throughout iOS to have a grouped UITableView where each cell displays a label alongside a text field. It is used to collect textual information from the user, e.g a username and password when logging in to a service.

Does the iOS framework provide this boilerplate UITableViewCell, or will I have to create a custom cell myself? I've scoured the docs and open source libraries without any luck, and I'd rather not have to reinvent the wheel.

答:
Have you looked at ELCTextFieldCell?:

http://icodeblog.com/2011/01/04/elctextfieldcell-a-useful-tableviewcell-for-forms/
https://github.com/elc/ELCTextFieldCell

ContentLicense: CC BY-SA 2.5


问:
Why am I not getting "Prevent this page from creating additional dialogs" as part of prompt window in Google Chrome?
When run the same on Microsoft edge I am able to see it.
What do I need to change in the settings of Chrome browser?enter image description here

This is my code:

```<code>alert("Hello from the JS file");
var age;
var ageroot;

age=prompt("Enter your age");
</code>```

答:
Alert and Prompt boxes have native implementation on every browser, and are not customizable by using JavaScript or CSS.

So, Chrome doesn't have this checkbox in its implementation, while Edge has it. Also, it is completely in the hand of the browser to prevent such boxes in future.

Body:
When run the same on Microsoft edge I am able to see it.
What do I need to change in the settings of Chrome browser?enter image description here

This is my code:

alert("Hello from the JS file");
var age;
var ageroot;

age=prompt("Enter your age");


问:
How to call table.reloadData by didReceiveData() in session using Multipeer Connectivity (Swift 3)
I am struggling on a problem that when I receive data from session using Multipeer Connectivity framework, I want to update the data and reload the table of a view controller instantly.

Here are my codes for didReceiveData function of MPCHandler:

```<code>func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    NSLog("%@", "didReceive: \(data)")
    if var dict: [NSDictionary] = NSKeyedUnarchiver.unarchiveObject(with: data) as? [NSDictionary]{
        let d = dict.removeFirst()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.winnerDataController.syncWinnerFromDictionary(d: dict)

    }
}
</code>```

For sync function in WinnerDataController

```<code>func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!

    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    appDelegate.resultViewController.tableView.reloadData()
}
</code>```

I want to update and reload the table of resultViewContoller upon the receive of the data. However, when it goes to appDelegate.resultViewController.tableView.reloadData(), the console gives out fatal error: unexpectedly found nil while unwrapping an Optional value. I spent all day on figuring why the tableView is nil, yet still haven't got any ideas.

Could someone plz help. Thx

I tried the following codes as provided by @Hitesh Sultaniya: NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil) and func testing(notification: Notification){
        print("testing")
        self.tableView.reloadData()
    } in result view controller. Also, NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil) in WinnerDataController.

In the console, "testing" is printed. However, after a few seconds,
"This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes"
is shown.

Then, I tried this:

```<code>func testing(notification: Notification){
DispatchQueue.global(qos: .userInitiated).async{
   self.tableView.reloadData()
}
</code>```

}

Now, no error is shown. But the table is still not yet reloaded...

答:
In resultViewController you can set Notification observer to reload tableview

you can set in this manner

// Register and add observer in result view controller

```<code> NotificationCenter.default.addObserver(self, selector: #selector(self.reloadTableView(_:)), name: NSNotification.Name(rawValue: "<Your Notfication Name>"), object: nil)

 // handle notification
 func reloadTableView(_ notification: NSNotification) {

  //relaod your table view
 }
</code>```

And when you are done with receiving data you can post notification like this

```<code>NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil)
</code>```

So this will post notification that you have set in result view controller and then your task will be performed

Note : This is just pseudo code so might contain error

If you application making UI changes that where you make UI changes while performing this task
And I think you will also need to fetch data from database again before reloading table view because as per your code that you have provided in question you directly reloading table.
You can check for current thread like this,

```<code> if (Thread.isMainThread == true)
 {
                    //Perform UI Task
 }
 else
 {
      //Dispatch for main queue with synchronous not asynchronous and then update the UI
 }
</code>```

Hope this helps

Body:
I am struggling on a problem that when I receive data from session using Multipeer Connectivity framework, I want to update the data and reload the table of a view controller instantly.

Here are my codes for didReceiveData function of MPCHandler:

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    NSLog("%@", "didReceive: \(data)")
    if var dict: [NSDictionary] = NSKeyedUnarchiver.unarchiveObject(with: data) as? [NSDictionary]{
        let d = dict.removeFirst()
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.winnerDataController.syncWinnerFromDictionary(d: dict)

    }
}

For sync function in WinnerDataController

func syncWinnerFromDictionary(d: NSDictionary){
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let context = appDelegate.persistentContainer.viewContext
    let entityDescription = NSEntityDescription.entity(forEntityName: "Winner", in: context)!

    let winner: Winner = NSManagedObject(entity: entityDescription, insertInto: context) as! Winner
    winner.setValue(d.value(forKey: "index"), forKey: "index")
    winner.setValue(d.value(forKey: "dept"), forKey: "dept")
    winner.setValue(d.value(forKey: "name"), forKey: "name")
    save()
    appDelegate.resultViewController.tableView.reloadData()
}

I want to update and reload the table of resultViewContoller upon the receive of the data. However, when it goes to appDelegate.resultViewController.tableView.reloadData(), the console gives out fatal error: unexpectedly found nil while unwrapping an Optional value. I spent all day on figuring why the tableView is nil, yet still haven't got any ideas.

Could someone plz help. Thx

I tried the following codes as provided by @Hitesh Sultaniya: NotificationCenter.default.addObserver(self, selector: #selector(testing), name: NSNotification.Name(rawValue: "syncWinner"), object: nil) and func testing(notification: Notification){
        print("testing")
        self.tableView.reloadData()
    } in result view controller. Also, NotificationCenter.default.post(name: NSNotification.Name(rawValue: "syncWinner"), object: nil) in WinnerDataController.

In the console, "testing" is printed. However, after a few seconds,
"This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes"
is shown.

Then, I tried this:

func testing(notification: Notification){
DispatchQueue.global(qos: .userInitiated).async{
   self.tableView.reloadData()
}

}

Now, no error is shown. But the table is still not yet reloaded...

Body:
In resultViewController you can set Notification observer to reload tableview

you can set in this manner

// Register and add observer in result view controller

 NotificationCenter.default.addObserver(self, selector: #selector(self.reloadTableView(_:)), name: NSNotification.Name(rawValue: "<Your Notfication Name>"), object: nil)

 // handle notification
 func reloadTableView(_ notification: NSNotification) {

  //relaod your table view
 }

And when you are done with receiving data you can post notification like this

NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil)

So this will post notification that you have set in result view controller and then your task will be performed

Note : This is just pseudo code so might contain error

If you application making UI changes that where you make UI changes while performing this task
And I think you will also need to fetch data from database again before reloading table view because as per your code that you have provided in question you directly reloading table.
You can check for current thread like this,

 if (Thread.isMainThread == true)
 {
                    //Perform UI Task
 }
 else
 {
      //Dispatch for main queue with synchronous not asynchronous and then update the UI
 }

Hope this helps


问:
Angular - Get the format, as string, used to display dates according to locale
How can I get the format, as a string, used by Angular to display dates ? I use the date pipe after setting LOCALE_ID in my app.module.

Now I'd like to retrieve the "dd/mm/yyyy" string, to put in my input placeholders.

Basically, what's described here but for Angular.

Thanks

[edit]

To make it more explicit, I'm not looking for a way to format dates, that's already done (with the native date pipe). I want the string that represents the format being used by this pipe.

Because I'd like my datepicker placeholder to be like

"Date (format: XXXXXX)"

and I want the "XXXXXX" part to be correct (i.e. "jj/mm/aaaa" for french, "mm/dd/yyyy" for english)

答:
If you want to declaratively format a date within your template:

```<code>{{ today | date: 'dd/MM/yyyy' }}
</code>```

If you want to imperatively get the formatted date within code:

```<code>import { DatePipe } from '@angular/common';
// in your component class
var date = new DatePipe().transform(today, 'dd/MM/yyyy')
</code>```

Body:
If you want to declaratively format a date within your template:

{{ today | date: 'dd/MM/yyyy' }}

If you want to imperatively get the formatted date within code:

import { DatePipe } from '@angular/common';
// in your component class
var date = new DatePipe().transform(today, 'dd/MM/yyyy')


问:
Recursive traversal of 2d array to find unique paths
I need to traverse a 2D-Array of 0's (which represent open pathways) and 1's which represent walls. I have to calculate the number of unique paths from (0,0) to (N-1,N-1) of an NxN Grid. I have written a recursive method to do this however i cannot figure out why the traversal part of my method (i.e the straight, left and right movements) are not working as expected:

```<code>    public static void TraversePath(int [][] Grid, boolean[][] isTraversed, int column, int row) {
    if(row < 0 || column < 0 || row > Grid[0].length || column > Grid[0].length )
        return; // if you go out of bounds
    if(isTraversed[column][row] == true)
        return; // if you have already been to the point
    if(Grid[column][row]==1) {
        isTraversed[column][row] = true; // if the current point is a wall mark it as traversed
        return;
    }
    if(Grid[column][row]!=1 && (row == Grid[0].length-1 && column == Grid[0].length-1)) { //if you get to an endpoint that isn't a wall
        uniquePaths++; //counter that tallys the unique paths
        isTraversed[column][row] = true;
        return;
    }

    TraversePath(Grid,column,row+1);//Straight
    TraversePath(Grid,column-1, row);//Left
    TraversePath(Grid,column+1, row);//Right

}

public static void main(String[] args) {
    int [][]Grid = new int[][]
            {
        {0,1,1,0},
        {0,0,1,0},
        {0,0,0,0},
        {0,1,1,0}
            };
    boolean[][] isTraversed = new boolean[Grid.length][Grid.length];
    for(int i = 0; i < Grid.length; i++) {
        for(int j = 0; j< Grid.length; j++)
            isTraversed[i][j] = false;
    }
    TraversePath(Grid,isTraversed,0,0);
    System.out.println(uniquePaths);

}
</code>```

I keep getting a StackOverFlow error (hey, sounds familiar) when I run this code. I figure it probably has something to do with how I am marking the edges as visited in the isTraversed boolean graph but I am not sure. Any help would be super appreciated.

This is the main method that I'm using to test the array, it's a simple 4x4 grid with 2 unique paths to (3,3).

答:
There are a couple of errors in this code, but the main problem is that you do not set isTraversed[column][row] = true if you just make a normal step without running into any of the if-statements.

Another big problem is, that the isTraversed array is shared across different search paths. This means that a grid-field visited in one branch of the iteration cannot be visited in another branch. Ultimately, your result will thus be always at most 1. In order to avoid this you could make a deep copy of isTraversed just before you enter the next iteration step.

```<code>boolean[][] isTraversedCopy = new boolean[isTraversed.length][isTraversed[0].length];
for(int i=0; i<isTraversed.length; i++)
      for(int j=0; j<isTraversed[i].length; j++)
          isTraversedCopy[i][j]=isTraversed[i][j];

TraversePath(Grid,isTraversedCopy, column,row+1);//Straight
TraversePath(Grid,isTraversedCopy, column-1, row);//Left
TraversePath(Grid,isTraversedCopy, column+1, row);//Right
</code>```

Other problems are:

TraversePath(Grid,column,row+1);//Straight and the following lines are missing an argument (isTraversed)

in the first if-statement it should be
if(row < 0 || column < 0 || row >= Grid[0].length || column >= Grid[0].length)

Why is there no possibility to move to the bottom?

Optional but this will make readability of your code easier: You should change row and column to make it consistent to your representation of the gridworld and with the normal use of 2d-arrays. Additionally, your definition of straight, left, right is a bit confusing and does not fit to the grid definition.

Body:
I need to traverse a 2D-Array of 0's (which represent open pathways) and 1's which represent walls. I have to calculate the number of unique paths from (0,0) to (N-1,N-1) of an NxN Grid. I have written a recursive method to do this however i cannot figure out why the traversal part of my method (i.e the straight, left and right movements) are not working as expected:

    public static void TraversePath(int [][] Grid, boolean[][] isTraversed, int column, int row) {
    if(row < 0 || column < 0 || row > Grid[0].length || column > Grid[0].length )
        return; // if you go out of bounds
    if(isTraversed[column][row] == true)
        return; // if you have already been to the point
    if(Grid[column][row]==1) {
        isTraversed[column][row] = true; // if the current point is a wall mark it as traversed
        return;
    }
    if(Grid[column][row]!=1 && (row == Grid[0].length-1 && column == Grid[0].length-1)) { //if you get to an endpoint that isn't a wall
        uniquePaths++; //counter that tallys the unique paths
        isTraversed[column][row] = true;
        return;
    }

    TraversePath(Grid,column,row+1);//Straight
    TraversePath(Grid,column-1, row);//Left
    TraversePath(Grid,column+1, row);//Right

}

public static void main(String[] args) {
    int [][]Grid = new int[][]
            {
        {0,1,1,0},
        {0,0,1,0},
        {0,0,0,0},
        {0,1,1,0}
            };
    boolean[][] isTraversed = new boolean[Grid.length][Grid.length];
    for(int i = 0; i < Grid.length; i++) {
        for(int j = 0; j< Grid.length; j++)
            isTraversed[i][j] = false;
    }
    TraversePath(Grid,isTraversed,0,0);
    System.out.println(uniquePaths);

}

I keep getting a StackOverFlow error (hey, sounds familiar) when I run this code. I figure it probably has something to do with how I am marking the edges as visited in the isTraversed boolean graph but I am not sure. Any help would be super appreciated.

This is the main method that I'm using to test the array, it's a simple 4x4 grid with 2 unique paths to (3,3).

Body:
There are a couple of errors in this code, but the main problem is that you do not set isTraversed[column][row] = true if you just make a normal step without running into any of the if-statements.

Another big problem is, that the isTraversed array is shared across different search paths. This means that a grid-field visited in one branch of the iteration cannot be visited in another branch. Ultimately, your result will thus be always at most 1. In order to avoid this you could make a deep copy of isTraversed just before you enter the next iteration step.

boolean[][] isTraversedCopy = new boolean[isTraversed.length][isTraversed[0].length];
for(int i=0; i<isTraversed.length; i++)
      for(int j=0; j<isTraversed[i].length; j++)
          isTraversedCopy[i][j]=isTraversed[i][j];

TraversePath(Grid,isTraversedCopy, column,row+1);//Straight
TraversePath(Grid,isTraversedCopy, column-1, row);//Left
TraversePath(Grid,isTraversedCopy, column+1, row);//Right

Other problems are:

TraversePath(Grid,column,row+1);//Straight and the following lines are missing an argument (isTraversed)

in the first if-statement it should be
if(row < 0 || column < 0 || row >= Grid[0].length || column >= Grid[0].length)

Why is there no possibility to move to the bottom?

Optional but this will make readability of your code easier: You should change row and column to make it consistent to your representation of the gridworld and with the normal use of 2d-arrays. Additionally, your definition of straight, left, right is a bit confusing and does not fit to the grid definition.


问:
Why haven't modern compilers removed the need for expression templates?
The standard pitch for expression templates in C++ is that they increase efficiency by removing unnecessary temporary objects. Why can't C++ compilers already remove these unnecessary temporary objects?

This is a question that I think I already know the answer to but I want to confirm since I couldn't find a low-level answer online.

Expression templates essentially allow/force an extreme degree of inlining. However, even with inlining, compilers cannot optimize out calls to operator new and operator delete because they treat those calls as opaque since those calls can be overridden in other translation units. Expression templates completely remove those calls for intermediate objects.

These superfluous calls to operator new and operator delete can be seen in a simple example where we only copy:

```<code>#include <array>
#include <vector>

std::vector<int> foo(std::vector<int> x)
{
    std::vector<int> y{x};
    std::vector<int> z{y};
    return z;
}

std::array<int, 3> bar(std::array<int, 3> x)
{
    std::array<int, 3> y{x};
    std::array<int, 3> z{y};
    return z;
}
</code>```

In the generated code, we see that foo() compiles to a relatively lengthy function with two calls to operator new and one call to operator delete while bar() compiles to only a transfer of registers and doesn't do any unnecessary copying.

Is this analysis correct?

Could any C++ compiler legally elide the copies in foo()?

答:
However, even with inlining, compilers cannot optimize out calls to operator new and operator delete because they treat those calls as opaque since those calls can be overridden in other translation units.

since c++14, this is no more true, allocation calls can be optimized-out/reused under certain conditions:

[expr.new#10] An implementation is allowed to omit a call to a replaceable global allocation function. When it does so, the storage is instead provided by the implementation or provided by extending the allocation of another new-expression.[conditions follows]

So foo() may be legally optimized to something equivalent to bar() nowadays ...

Expression templates essentially allow/force an extreme degree of inlining

IMO the point of expression templates is not much about inlining per se, it's rather exploiting the symmetries of the type system of the domain specific language the expression models.

For example, when you multiply three, say, hermitian matrices, an expression template can use a space-time optimized algorithm exploiting the fact that the product is associative and that hermitian matrices are adjoint-symmetric, resulting in a reduction of total operation count (and possibly even better accuracy). And all this, occurs at compile time.

Conversely, a compiler cannot know what an hermitian matrix is, it's constrained evaluating the expression the brute way (according to your implementation floating point semantics).

Body:
The standard pitch for expression templates in C++ is that they increase efficiency by removing unnecessary temporary objects. Why can't C++ compilers already remove these unnecessary temporary objects?

This is a question that I think I already know the answer to but I want to confirm since I couldn't find a low-level answer online.

Expression templates essentially allow/force an extreme degree of inlining. However, even with inlining, compilers cannot optimize out calls to operator new and operator delete because they treat those calls as opaque since those calls can be overridden in other translation units. Expression templates completely remove those calls for intermediate objects.

These superfluous calls to operator new and operator delete can be seen in a simple example where we only copy:

#include <array>
#include <vector>

std::vector<int> foo(std::vector<int> x)
{
    std::vector<int> y{x};
    std::vector<int> z{y};
    return z;
}

std::array<int, 3> bar(std::array<int, 3> x)
{
    std::array<int, 3> y{x};
    std::array<int, 3> z{y};
    return z;
}

In the generated code, we see that foo() compiles to a relatively lengthy function with two calls to operator new and one call to operator delete while bar() compiles to only a transfer of registers and doesn't do any unnecessary copying.

Is this analysis correct?

Could any C++ compiler legally elide the copies in foo()?


问:
saving the files in a variable and deleting the files
I am trying to delete old files, I first need to store the files in a variable and delete them one by one, my code works for normal files but if filename has white spaces in it, it cant delete that file and throws an error

code-

```<code>OLD_FILES=`find . -name "*.txt" -type f -newermt $2000-01-01 ! -newermt $2017-12-12`
for i in $OLD_FILES
   do
     rm $i
   done
</code>```

I can't use

```<code>OLD_FILES=`find . -name "*.$FILE_TYPE" -type f -newermt $START_DATE ! -newermt $DATE -delete `
</code>```

because find and delete needs to be separate functions and to avoid code repetition

答:
Filenames on UNIX may contain more or less any character, especially characters which are used by the shell to split input into words, like whitespace and newlines. If you use a for in loop, word splitting happens and that's what you are seeing.

I recommend to use the -print0 option of find which would separate files by null bytes and then use while read with the null byte as the delimiter to read them in the shell one by one:

```<code>find ... -print0 | while read -d $'\0' file ; do
    do_something "${file}"
    rm "${file}"
done
</code>```

Body:
I am trying to delete old files, I first need to store the files in a variable and delete them one by one, my code works for normal files but if filename has white spaces in it, it cant delete that file and throws an error

code-

OLD_FILES=`find . -name "*.txt" -type f -newermt $2000-01-01 ! -newermt $2017-12-12`
for i in $OLD_FILES
   do
     rm $i
   done

I can't use

OLD_FILES=`find . -name "*.$FILE_TYPE" -type f -newermt $START_DATE ! -newermt $DATE -delete `

because find and delete needs to be separate functions and to avoid code repetition

Body:
Filenames on UNIX may contain more or less any character, especially characters which are used by the shell to split input into words, like whitespace and newlines. If you use a for in loop, word splitting happens and that's what you are seeing.

I recommend to use the -print0 option of find which would separate files by null bytes and then use while read with the null byte as the delimiter to read them in the shell one by one:

find ... -print0 | while read -d $'\0' file ; do
    do_something "${file}"
    rm "${file}"
done


问:
RStudio does not display any output in console after entering code
The problem is that when I run the code, there's no return in the console; I mean it does run the code, but does not return any output.

For example, if I write

```<code>v <- c(1, 2, 3, 4, 5)
v
</code>```

I would expect in return

```<code>[1] 1 2 3 4 5
</code>```

But it's not working.

I have version RStudio Version 0.98.1079 and R Version 3.1.1

答:
This is a very old question, but I just had the same problem with a different cause, so I thought I would describe it here case it should be useful to someone else. I was getting the regular command prompt, with nothing more, no matter what I typed at the command line. I tried multiple returns, escape, sink, traceback, closeAllConnections (which did give me a response, "error: unexpected ) in (), but then went back to the command prompt and ignored a second traceback).

Anyway after half an hour or so of pulling my hair out, up pops "View(Mid2)". Mid2 is a tibble with 8.5 million observations of 88 numeric variables. I must have tapped it in the environment pane accidentally. I suppose it just took that long for the viewer to render it. I assume that all the other things I did hit at once, because RStudio crashed immediately thereafter.

The interesting thing about this particular version of the problem is what didn't happen. The red stop sign in the upper right of the console window, that lights when R is busy, didn't light. That is unfortunate -- but understandable, if the RStudio viewer is a different process. But also, when my computer is working hard on a really big computation or IO task, the fan usually starts, but it didn't. Don't know why. . I took its absence, incorrectly, to mean no such computation was underway.

ContentLicense: CC BY-SA 4.0

Body:
The problem is that when I run the code, there's no return in the console; I mean it does run the code, but does not return any output.

For example, if I write

v <- c(1, 2, 3, 4, 5)
v

I would expect in return

[1] 1 2 3 4 5

But it's not working.

I have version RStudio Version 0.98.1079 and R Version 3.1.1


问:
How to generate git sha1 of current repository
I am trying to generate the current git sha1 of a repository.
I don't want the last commit sha1 that can be generated using a set of git command. I want the sha1 that will be used in the next commit (obviously if files are not changed).

I would like to be able to generate an header file containing a define of the sha1 repository. This will allows me to match executable with relative git commit and viceversa.

The problem is that not every executable is created with a stable commit (especially during development phase).

For this reason I choose to include both:
- Last commit sha1
- Current repository sha1

If they match it means that the current  executable is created using a stable commit. Otherwise it means that you can just know what is the starting commit of your executable.

Can someone help me?

答:
https://gist.github.com/masak/2415865

I just found out (using the link above) that commit sha1 in git depends on commit author and not just by the repository files. So I think that achieving what I want is not possible.


问:
Java streams: Add to map but avoid mutation
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

```<code>class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}
</code>```

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

答:
If you avoid the GroupedDataObject and simply want a map with a key and a list you can use Collectors.groupingBy that you have been looking into.

Collectors.groupingBy will allow you to do this:

```<code>List<SomeObject> list = getSomeList();

Map<SomeKey, List<SomeObject>> = list.stream().collect(Collectors.groupingBy(SomeObject::getKeyMethod));
</code>```

This will require SomeKey to have proper implementations of equals and hashValue

Body:
I often find myself in a situation where I need to create a Map of objects from a Set or List.
The key is usually some String or Enum or the like, and the value is some new object with data lumped together.
The usual way of doing this, for my part, is by first creating the Map<String, SomeKeyValueObject> and then iterating over the Set or List I get in and mutate my newly created map.

Like the following example:

class Example {
   Map<String, GroupedDataObject> groupData(final List<SomeData> list){
      final Map<String, GroupedDataObject> map = new HashMap<>();
      for(final SomeData data : list){
         final String key = data.valueToGroupBy();
         map.put(key, GroupedDataObject.of(map.get(key), data.displayName(), data.data()));
      }
      return map;
   }

}

class SomeData {
   private final String valueToGroupBy;
   private final Object data;
   private final String displayName;

   public SomeData(final String valueToGroupBy, final String displayName, final Object data) {
      this.valueToGroupBy = valueToGroupBy;
      this.data = data;
      this.displayName = displayName;
   }

   public String valueToGroupBy() {
      return valueToGroupBy;
   }

   public Object data() {
      return data;
   }

   public String displayName() {
      return displayName;
   }
}

class GroupedDataObject{

   private final String key;
   private final List<Object> datas;

   private GroupedDataObject(final String key, final List<Object> list) {
      this.key = key;
      this.datas = list;
   }

   public static GroupedDataObject of(final GroupedDataObject groupedDataObject, final String key, final Object data) {
      final List<Object> list = new ArrayList<>();
      if(groupedDataObject != null){
         list.addAll(groupedDataObject.datas());
      }
      list.add(data);
      return new GroupedDataObject(key, list);
   }

   public String key() {
      return key;
   }

   public List<Object> datas() {
      return datas;
   }
}

This feels very unclean. We create a map, and then mutate it over and over.

I've taken a liking to java 8s use of Streams and creating non-mutating data structures (or rather, you don't see the mutation). So is there a way to turn this grouping of data into something that uses a declarative approach rather than the imperative way?

I tried to implement the suggestion in https://stackoverflow.com/a/34453814/3478016 but I seem to be stumbling. Using the approach in the answer (the suggestion of using Collectors.groupingBy and Collectors.mapping) I'm able to get the data sorted into a map. But I can't group the "datas" into one and the same object.

Is there some way to do it in a declarative way, or am I stuck with the imperative?

Body:
If you avoid the GroupedDataObject and simply want a map with a key and a list you can use Collectors.groupingBy that you have been looking into.

Collectors.groupingBy will allow you to do this:

List<SomeObject> list = getSomeList();

Map<SomeKey, List<SomeObject>> = list.stream().collect(Collectors.groupingBy(SomeObject::getKeyMethod));

This will require SomeKey to have proper implementations of equals and hashValue


问:
Calling remote method in spring with parameters
I have a class annoted with Service Annotation on server 1 .

```<code>@Service
public class MainHandler implements AbstractHandler {

   @Autowired
   private ServiceLocal defaultService;

   @Override
   public boolean execute(HttpServletRequest request, HttpServletResponse response) throws MsisdnServiceException {
          System.out.println("The default Request" + request);
   }
}
</code>```

I want to call this method from other remote server after passing the request and get the response from this  , what is the way to do in spring .

答:
You can use spring's RestTemplate to make communication with the servers.

First you need to create a controller on server 1 backend to get data from server 2:

```<code>@RestController
public class MyController {
    @RequestMapping(value = "/endpoint", method = RequestMethod.POST)
    String execute(@RequestBody MyClass object) {
          System.out.println("Your data" + object);
        }
    }
</code>```

On server 2 backend create a method that make a REST call to server 1's endpoint with RestTemplate:

```<code>void request() {
    String url = "http://localhost:8080/endpoint";

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-Type", "application/json");

    JSONObject json = new JSONObject();
    json.put("name", "yourName");
    json.put("email", "name@gmail.com");

    HttpEntity < String > httpEntity = new HttpEntity < String > (json.toString(), httpHeaders);

    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.postForObject(url, httpEntity, String.class);
}
</code>```

Body:
I have a class annoted with Service Annotation on server 1 .

@Service
public class MainHandler implements AbstractHandler {

   @Autowired
   private ServiceLocal defaultService;

   @Override
   public boolean execute(HttpServletRequest request, HttpServletResponse response) throws MsisdnServiceException {
          System.out.println("The default Request" + request);
   }
}

I want to call this method from other remote server after passing the request and get the response from this  , what is the way to do in spring .

Body:
You can use spring's RestTemplate to make communication with the servers.

First you need to create a controller on server 1 backend to get data from server 2:

@RestController
public class MyController {
    @RequestMapping(value = "/endpoint", method = RequestMethod.POST)
    String execute(@RequestBody MyClass object) {
          System.out.println("Your data" + object);
        }
    }

On server 2 backend create a method that make a REST call to server 1's endpoint with RestTemplate:

void request() {
    String url = "http://localhost:8080/endpoint";

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-Type", "application/json");

    JSONObject json = new JSONObject();
    json.put("name", "yourName");
    json.put("email", "name@gmail.com");

    HttpEntity < String > httpEntity = new HttpEntity < String > (json.toString(), httpHeaders);

    RestTemplate restTemplate = new RestTemplate();
    String response = restTemplate.postForObject(url, httpEntity, String.class);
}


问:
In VBA, how to handle same error differently from different variables?

I have a VBA function in Access in the After_Update for a combobox that has two variables. The first one comes from the combobox and the second is a query result based on the first. I created some error handling to deal with Null values, but I would like to handle the errors differently depending on which value is Null. Sometimes users will enter a name in the combobox and then delete it, which makes the variable Null. If childID is Null that is not a problem and  I would like the function to simply exit. If visitID is Null, I would like it to display the error message box.  What I came up with displays the error for Null values from both variables.

```<code>On Error GoTo Error_Handle

childID = Me.cmbChildSearchFirst.Column(0)
visitid = DLookup("Visit.[VisitID]", "Q_VisitID_from_ChildID", "[ChildID] =" & childID)

Error_Handle:
If Err.Number = 94 Then
    MsgBox ("Child is not associated with any visit")
    Exit Sub
End If
</code>```

答:
Basic outline:</p>

```<code>childID = Me.cmbChildSearchFirst.Column(0)

'proceed only if not null.
If Not IsNull(childID) Then
    If Not IsNull(DLookup("Visit.[VisitID]", "Q_VisitID_from_ChildID", "[ChildID] =" & childID)) Then
        ....
    Else
        MsgBox ("Child is not associated with any visit")
        Exit Sub
    End If
End If
</code>```

Body:
I have a VBA function in Access in the After_Update for a combobox that has two variables. The first one comes from the combobox and the second is a query result based on the first. I created some error handling to deal with Null values, but I would like to handle the errors differently depending on which value is Null. Sometimes users will enter a name in the combobox and then delete it, which makes the variable Null. If childID is Null that is not a problem and  I would like the function to simply exit. If visitID is Null, I would like it to display the error message box.  What I came up with displays the error for Null values from both variables.

On Error GoTo Error_Handle

childID = Me.cmbChildSearchFirst.Column(0)
visitid = DLookup("Visit.[VisitID]", "Q_VisitID_from_ChildID", "[ChildID] =" & childID)

Error_Handle:
If Err.Number = 94 Then
    MsgBox ("Child is not associated with any visit")
    Exit Sub
End If

Body:
Basic outline:

childID = Me.cmbChildSearchFirst.Column(0)

'proceed only if not null.
If Not IsNull(childID) Then
    If Not IsNull(DLookup("Visit.[VisitID]", "Q_VisitID_from_ChildID", "[ChildID] =" & childID)) Then
        ....
    Else
        MsgBox ("Child is not associated with any visit")
        Exit Sub
    End If
End If


问:
Nuget package sources not being saved
My NuGet package manager cannot save new or find existing package sources.

The location where the package sources are saved %appdata%\NuGet\nuget.config is not getting updated since the problem started. Deleting it does not re-create it when I try adding a new package source through the Visual Studio -> Package Manager Sources dialog.

"Package Manager sources" dialog always shows empty on trying to save something and re-opening the dialog.

This problem started on my laptop after changing my corporate password from my office desktop computer (which does not have this issue).

Re-installing "Nuget Package Manager" did not help. Re-installing Visual Studio did not help.

答: I just deleted the package source that didn't want to update, and readded it.</p>

Title: Nuget package sources not being saved


问:
Show drop down values of a select option based on another select option
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working. </p>

```<code>   <div class="vali-form">
        <div class="col-md-6 form-group2">

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" <label class='control-label'>Select State</label>";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

        </div>
        <div class="col-md-6 form-group2"  id="response">

         <label class='control-label'>City:</label>
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

        </div>
        <div class="clearfix"> </div>
        </div>
</code>```

<p>jQuery-AJAX code is below.         </p>

```<code>     <script type="text/javascript" src="http://code.jquery.com/jquery.js">
  </script>
  <script type="text/javascript">
  $(document).ready(function(){
   $("select.selectstate").change(function(){
    var selectedstate = $(".selectstate option:selected").val();
    $.ajax({
        type: "POST",
        url: "locpac.php",
        data: { selectstate : selectedstate }
    }).done(function(data){
        $("#response").html(data);
    });
   });
   });
   </script>
</code>```

答:
There so many problems with your code so you can try the below one instead.

```<code><?php
   include("connection.php");
?>
<div class="form-group">
    <div class="row">
        <label>State:</label><br/>
        <select name="selectstate" id="State-list" class="demoInputBox" onChange="getCity(this.value);">
        <option value="">Select State</option>
        <?php
        $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }

        ?>
        </select>
    </div>
    <div class="row">
        <label>City:</label><br/>
        <select name="City" id="response" class="demoInputBox">
        <option value="">Select City</option>
        </select>
    </div>
</div>

<script>
function getCity(val) {
    $.ajax({
    type: "POST",
    url: "locpac.php",
    data:'selectstate ='+val,
    success: function(data){
        $("#response").html(data);
    }
    });
}
</script>
</code>```

and in locpac.php you can write the code only for the option instead of the complete dropdown.

Body:
I have two dropdown select option. First is for select State and second is for select city. When any one select from state dropdown then related content should be shown on second select option (that will be related city.). I have some code, but it is not working.

        <?php
   include("connection.php");
   $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        echo" Select State";
        echo" <select required name='selectstate'>";
        echo"<option>Select</option>";
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }
        echo" </select>";
       ?>

         City:
     <select>

            <?php
   if(isset($_POST["selectstate"])){
// Capture selected country
$selectstate = $_POST["selectstate"];

// Define country and city array
$query1=mysql_query("select * from location_master where id='$selectstate'") or die (mysql_error());

        $row1=mysql_fetch_array($query1);

    // Display city dropdown based on country name
   if($selectstate !== 'Select'){

    foreach($row1[$selectstate] as $value){
        echo "<option>". $value . "</option>";
    }

   }
   }
   ?>

 </select>

jQuery-AJAX code is below.

Body:
There so many problems with your code so you can try the below one instead.

<?php
   include("connection.php");
?>
<div class="form-group">
    <div class="row">
        <label>State:</label><br/>
        <select name="selectstate" id="State-list" class="demoInputBox" onChange="getCity(this.value);">
        <option value="">Select State</option>
        <?php
        $query1=mysql_query("select * from location_master where parent_id='0' ORDER BY location") or die (mysql_error());
        while($row1=mysql_fetch_array($query1))
        {

            echo"<option value='".$row1['id']."'>".$row1['location']."</option>";
        }

        ?>
        </select>
    </div>
    <div class="row">
        <label>City:</label><br/>
        <select name="City" id="response" class="demoInputBox">
        <option value="">Select City</option>
        </select>
    </div>
</div>

<script>
function getCity(val) {
    $.ajax({
    type: "POST",
    url: "locpac.php",
    data:'selectstate ='+val,
    success: function(data){
        $("#response").html(data);
    }
    });
}
</script>

and in locpac.php you can write the code only for the option instead of the complete dropdown.


问:
Azure AD B2C - Redirect the user to the login page based on the directory it belongs when using custom Policy
My application contains users from B2B and B2C directory. It is using Azure B2C Login which is created using custom policy for this purpose. Currently, it displays the B2B directory button in B2C Login screen. In my application we can identify if the user belongs to B2C or B2B directory.

My requirement is that if the user is identified as B2B user then it should redirect to the B2B login screen directly instead of B2C login and clicking on B2B Sign in button.

Is there any way by which I can accomplish this in my application?

答:
You can assign a <Domain> to your B2B <ClaimsProvider>. Then,  pass it in as a domain_hint which will take the user directly to that IDP.

This is how Facebook is set up in a starter pack and you could try it there and copy the required elements.

<ClaimsProvider>

    <Domain>facebook.com</Domain>
    ...
</ClaimsProvider>
```

Body:
You can assign a <Domain> to your B2B <ClaimsProvider>. Then,  pass it in as a domain_hint which will take the user directly to that IDP.

This is how Facebook is set up in a starter pack and you could try it there and copy the required elements.

<ClaimsProvider>
    <!-- The following Domain element allows this profile to be used if the request comes with domain_hint
       query string parameter, e.g. domain_hint=facebook.com  -->
    <Domain>facebook.com</Domain>
    ...
</ClaimsProvider>


问:
Alignment of Axis text in ggpplot2
I have the following bar plot using ggplot2.

We can observe that the x-axis text is not aligned with the x-axis rather it is centrally aligned. How do I get all the x-axis text aligned with the x-axis?
I have tried changing the values in axis.text.x = element_text(angle = 90, vjust = 1, hjust=1) as discussed in Align axis label on the right with ggplot2 but of no avail.

The code used for plotting is given below:

```<code> p <- ggplot(plot_solver,aes(x=name,round(value,2),fill=variable,label=round(value,2)))+
    geom_bar(stat="identity",width= 0.7)+
    theme_bw()+geom_text(size = 1, position = position_stack(vjust = 0.5))

    p + theme(legend.position=c(.3,0.85),legend.title = element_blank(),
    legend.text=element_text(size=8),legend.direction = 'horizontal',
    axis.title.y = element_text(size = 8,face = "bold"),
    axis.text.x = element_text(angle = 90, vjust = 1, hjust=1),
    axis.text.y = element_text(size = 9),axis.title.x=element_blank() )+
    guides(fill=guide_legend(title="Formats"))+
    scale_fill_manual(values=rainbow(4),labels=c("X ","Y  ","Z ","U "))+
    guides(fill=guide_legend(keywidth=0.2,keyheight=0.1,default.unit="inch",nrow=2))+
    ylab("Speedup")+theme(plot.margin=unit(c(1.0,0.6,0.6,0),"mm"))+
    theme(legend.key = element_blank())+
    theme(legend.background = element_rect(colour = "black"))+
    theme(panel.border = element_rect(colour = "black"))
</code>```

The dput() of the data structure is given below for reproducing the data structure:

```<code>> dput(plot_solver)
structure(list(name = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L), .Label = c("12month1        ",
"amazon0312      ", "Andrews         ", "av41092         ", "bundle_adj     ",
"bundle1         ", "flickr          ", "Freescale1      ", "Ga3As3H12       ",
"hollywood-2009  ", "in-2004         ", "lhr71c          ", "mouse_gene     ",
"nemeth23        ", "rail4284        ", "RM07R           ", "SiO2            ",
"spal_004       ", "thermal2        ", "thermomech_TK  ", "torso1          ",
"TSOPF_RS_b2383", "wb-edu          ", "Zd_Jac2        "), class = "factor"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("solver_csr_50",
    "solver_hyb_50", "solver_csr_250", "solver_hyb_250"), class = "factor"),
    value = c(1.483853636, 0.833971405, 0.947560492, 2.403142882,
    1.626413472, 0.991467865, 2.538000882, 1.316118676, 1.221777675,
    1.078077417, 1.664918578, 1.212409967, 1.364104634, 1.017229312,
    3.149256956, 1.12104879, 1.242688247, 0.82382667, 1.118503136,
    1.008526996, 2.228076048, 1.068948907, 1.884906941, 1.105205313,
    1.120927241, 0.641889919, 1.046822614, 1.468693059, 1.500747131,
    1.25410977, 1.059699706, 0.910956693, 1.43968056, 1.397810123,
    1.094151621, 1.182516419, 1.626171249, 1.397388864, 2.440610373,
    1.035590769, 1.216158929, 1.257113662, 0.800255725, 0.962159854,
    2.946661991, 2.237199908, 0.96889509, 1.363652596, 1.483905263,
    0.893797519, 1.029405415, 2.471348689, 1.671715929, 1.00715098,
    2.69514063, 1.455418078, 1.235602809, 1.087707209, 1.763360364,
    1.250831883, 1.368235001, 1.028816823, 3.155078988, 1.131893099,
    1.268342707, 0.824145645, 1.215626973, 1.066510807, 2.300424627,
    1.075502897, 2.115832988, 1.105855239, 1.120966241, 0.687936797,
    1.137241238, 1.510377387, 1.542549251, 1.273947374, 1.125310773,
    1.007373319, 1.455971394, 1.410295887, 1.158845619, 1.219990993,
    1.631095127, 1.413306866, 2.44512233, 1.045608412, 1.24126571,
    1.257600401, 0.869744941, 1.017477853, 3.042344008, 2.250916734,
    1.087597561, 1.364454504)), row.names = c(NA, -96L), .Names = c("name",
"variable", "value"), class = "data.frame")
</code>```

答:
name variable has space.

```<code>library(stringr)
df$name <- str_replace_all(df$name, "\\s", '')
</code>```

Title: Alignment of Axis text in ggpplot2

Body:
I have the following bar plot using ggplot2.

We can observe that the x-axis text is not aligned with the x-axis rather it is centrally aligned. How do I get all the x-axis text aligned with the x-axis?
I have tried changing the values in axis.text.x = element_text(angle = 90, vjust = 1, hjust=1) as discussed in Align axis label on the right with ggplot2 but of no avail.

The code used for plotting is given below:

 p <- ggplot(plot_solver,aes(x=name,round(value,2),fill=variable,label=round(value,2)))+
    geom_bar(stat="identity",width= 0.7)+
    theme_bw()+geom_text(size = 1, position = position_stack(vjust = 0.5))

    p + theme(legend.position=c(.3,0.85),legend.title = element_blank(),
    legend.text=element_text(size=8),legend.direction = 'horizontal',
    axis.title.y = element_text(size = 8,face = "bold"),
    axis.text.x = element_text(angle = 90, vjust = 1, hjust=1),
    axis.text.y = element_text(size = 9),axis.title.x=element_blank() )+
    guides(fill=guide_legend(title="Formats"))+
    scale_fill_manual(values=rainbow(4),labels=c("X ","Y  ","Z ","U "))+
    guides(fill=guide_legend(keywidth=0.2,keyheight=0.1,default.unit="inch",nrow=2))+
    ylab("Speedup")+theme(plot.margin=unit(c(1.0,0.6,0.6,0),"mm"))+
    theme(legend.key = element_blank())+
    theme(legend.background = element_rect(colour = "black"))+
    theme(panel.border = element_rect(colour = "black"))

The dput() of the data structure is given below for reproducing the data structure:

> dput(plot_solver)
structure(list(name = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 7L,
8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L,
21L, 22L, 23L, 24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L,
11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L,
24L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L,
14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L, 1L, 2L,
3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L,
17L, 18L, 19L, 20L, 21L, 22L, 23L, 24L), .Label = c("12month1        ",
"amazon0312      ", "Andrews         ", "av41092         ", "bundle_adj     ",
"bundle1         ", "flickr          ", "Freescale1      ", "Ga3As3H12       ",
"hollywood-2009  ", "in-2004         ", "lhr71c          ", "mouse_gene     ",
"nemeth23        ", "rail4284        ", "RM07R           ", "SiO2            ",
"spal_004       ", "thermal2        ", "thermomech_TK  ", "torso1          ",
"TSOPF_RS_b2383", "wb-edu          ", "Zd_Jac2        "), class = "factor"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L,
    4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L), .Label = c("solver_csr_50",
    "solver_hyb_50", "solver_csr_250", "solver_hyb_250"), class = "factor"),
    value = c(1.483853636, 0.833971405, 0.947560492, 2.403142882,
    1.626413472, 0.991467865, 2.538000882, 1.316118676, 1.221777675,
    1.078077417, 1.664918578, 1.212409967, 1.364104634, 1.017229312,
    3.149256956, 1.12104879, 1.242688247, 0.82382667, 1.118503136,
    1.008526996, 2.228076048, 1.068948907, 1.884906941, 1.105205313,
    1.120927241, 0.641889919, 1.046822614, 1.468693059, 1.500747131,
    1.25410977, 1.059699706, 0.910956693, 1.43968056, 1.397810123,
    1.094151621, 1.182516419, 1.626171249, 1.397388864, 2.440610373,
    1.035590769, 1.216158929, 1.257113662, 0.800255725, 0.962159854,
    2.946661991, 2.237199908, 0.96889509, 1.363652596, 1.483905263,
    0.893797519, 1.029405415, 2.471348689, 1.671715929, 1.00715098,
    2.69514063, 1.455418078, 1.235602809, 1.087707209, 1.763360364,
    1.250831883, 1.368235001, 1.028816823, 3.155078988, 1.131893099,
    1.268342707, 0.824145645, 1.215626973, 1.066510807, 2.300424627,
    1.075502897, 2.115832988, 1.105855239, 1.120966241, 0.687936797,
    1.137241238, 1.510377387, 1.542549251, 1.273947374, 1.125310773,
    1.007373319, 1.455971394, 1.410295887, 1.158845619, 1.219990993,
    1.631095127, 1.413306866, 2.44512233, 1.045608412, 1.24126571,
    1.257600401, 0.869744941, 1.017477853, 3.042344008, 2.250916734,
    1.087597561, 1.364454504)), row.names = c(NA, -96L), .Names = c("name",
"variable", "value"), class = "data.frame")

Body:
name variable has space.

library(stringr)
df$name <- str_replace_all(df$name, "\\s", '')


问:
How to provide table name from textbox to Linq
I want to give table name from textbox to Linq :

```<code>      StudentDatabaseEntities empl = new StudentDatabaseEntities();

        var query = from g in empl.Teachers
                    where g.id == 1
                    select new
                    {
                        Teacher_Id = g.tech_id,
                        Teacher_Name = g.username,
                        Teach_password = g.password,
                        Teacher_contact = g.contact,
                        Teacher_secret = g.secret,

                        //Administrator_Id = g.Administrator.id,

                        Administrator_Name = g.Administrator.username,
                        Administrator_password=g.Administrator.password,
                        Administrator_contact=g.Administrator.contact,
                        Administrator_secret=g.Administrator.secret
                        //etc...
                    };
        dataGridView1.DataSource = query.ToList();
</code>```

In this example I want to give table name from textbox instead of Teacher .
Is it possible ?

答:
If you want to use the same query on different types, all types that you want to use should have all properties that you use in your query.

For instance, if you want to do the same query with Students, Students should also have tech_id, username, secret etc.

Normally you would do this using inheritance / composition or Interface. Something like:

```<code>interface IPersonData
{
    public int tech_id {get;}
    public string username {get;}
    ...
}
class Teacher : IPersonData {...}
class Student : IPersonData {...}
</code>```

Furthermore class StudentDataBaseEntities needs a function to select the proper entity based on entity type. So if you ask for "Teachers that ..." it should use empl.Teachers, and if you ask for "Students who ..." it should use empl.Students.

If you use Entity Framework, you can use class DbContext.Set for this. Otherwise you'll have to create a similar function yourself.

```<code>public static IQueryable<TSource> ToMyData<TSource>(this TSource source)
    where TSource : IPersonData
{
    return source
        .Where(sourceItem => sourceItem.Id == 1)
        .Select(sourceItem => new
        {
             Id = sourceItem.tech_id,
             Name = sourceItem.username,
             ...
        });
}

static IQueryable<TSource> ToMyData<TSource>(this DbContext dbContext)
     where TSource : IPersonData
{
    return dbContext.Set<TSource>().ToMyData();
}
</code>```

Or if you want some more type safety:

```<code>static IQueryable<TSource> ToMyData<TSource>(this DbContext dbContext)
     where TSource : IPersonData
{
    IQueryable<TSource> sourceData = dbContext.Set<TSource>();
    if (sourceData == null) throw new ...

    return sourceData.ToMyData();
}
</code>```

Usage would by:

```<code>IQueryable<Student> studentData = myDbContext.ToMyData<Student>();
IQueryable<Teacher> teacherData = myDbContext.TyMyData<Teacher>();
</code>```

But my StudentDataBaseEntities is not derived from DbContext!

In that case you'll have to create a function similar to DbContext.Set. You know exactly which entities your StudentDataBaseEntities supports.

In your StudentDataBaseEntities.

```<code>public IQueryable<TSource> GetTable<TSource>()
     where TSource : IPersonData
{
    return this.GetTable(typeof(TSource))
}

public IQueryable<TSource> GetTable(System.Type type)
{
     if (type == typeof(Teacher)) return this.Teachers;
     else if (type == typeof(Student)) return this.Students;
     ...

     // TODO: improve this code by using a switch statement
     // TODO: search stackoverflow how to do this for a type
}
</code>```

Body:
I want to give table name from textbox to Linq :

      StudentDatabaseEntities empl = new StudentDatabaseEntities();

        var query = from g in empl.Teachers
                    where g.id == 1
                    select new
                    {
                        Teacher_Id = g.tech_id,
                        Teacher_Name = g.username,
                        Teach_password = g.password,
                        Teacher_contact = g.contact,
                        Teacher_secret = g.secret,

                        //Administrator_Id = g.Administrator.id,

                        Administrator_Name = g.Administrator.username,
                        Administrator_password=g.Administrator.password,
                        Administrator_contact=g.Administrator.contact,
                        Administrator_secret=g.Administrator.secret
                        //etc...
                    };
        dataGridView1.DataSource = query.ToList();

In this example I want to give table name from textbox instead of Teacher .
Is it possible ?

Body:
If you want to use the same query on different types, all types that you want to use should have all properties that you use in your query.

For instance, if you want to do the same query with Students, Students should also have tech_id, username, secret etc.

Normally you would do this using inheritance / composition or Interface. Something like:

interface IPersonData
{
    public int tech_id {get;}
    public string username {get;}
    ...
}
class Teacher : IPersonData {...}
class Student : IPersonData {...}

Furthermore class StudentDataBaseEntities needs a function to select the proper entity based on entity type. So if you ask for "Teachers that ..." it should use empl.Teachers, and if you ask for "Students who ..." it should use empl.Students.

If you use Entity Framework, you can use class DbContext.Set for this. Otherwise you'll have to create a similar function yourself.

public static IQueryable<TSource> ToMyData<TSource>(this TSource source)
    where TSource : IPersonData
{
    return source
        .Where(sourceItem => sourceItem.Id == 1)
        .Select(sourceItem => new
        {
             Id = sourceItem.tech_id,
             Name = sourceItem.username,
             ...
        });
}

static IQueryable<TSource> ToMyData<TSource>(this DbContext dbContext)
     where TSource : IPersonData
{
    return dbContext.Set<TSource>().ToMyData();
}

Or if you want some more type safety:

static IQueryable<TSource> ToMyData<TSource>(this DbContext dbContext)
     where TSource : IPersonData
{
    IQueryable<TSource> sourceData = dbContext.Set<TSource>();
    if (sourceData == null) throw new ...

    return sourceData.ToMyData();
}

Usage would by:

IQueryable<Student> studentData = myDbContext.ToMyData<Student>();
IQueryable<Teacher> teacherData = myDbContext.TyMyData<Teacher>();

But my StudentDataBaseEntities is not derived from DbContext!

In that case you'll have to create a function similar to DbContext.Set. You know exactly which entities your StudentDataBaseEntities supports.

In your StudentDataBaseEntities.

public IQueryable<TSource> GetTable<TSource>()
     where TSource : IPersonData
{
    return this.GetTable(typeof(TSource))
}

public IQueryable<TSource> GetTable(System.Type type)
{
     if (type == typeof(Teacher)) return this.Teachers;
     else if (type == typeof(Student)) return this.Students;
     ...

     // TODO: improve this code by using a switch statement
     // TODO: search stackoverflow how to do this for a type
}


问:
AND/OR operator between numbers in Python
How do and/or operators work between numbers (or even strings)?

```<code>5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21
</code>```

How does the and operator work in such cases?

答:
AND/OR :

 5 and 7 #7

It check 5 first and found it is 'True' so it check for second also and return last one.

0 and 5 # 0

it check for first and found is zero so whatever will be next value it is always zero so it return 0

2 or 3 and 4 #2

first value is 2 ('True') and found OR So value is always true so return 2

(2 or 3) and 4 #4

now return 4.

Body:
How do and/or operators work between numbers (or even strings)?

5 and 7  # this returns 7
7 and 5  # this returns 5
21 and 4 # this returns 4
4 and 21 # this returns 21

How does the and operator work in such cases?