问:
boostrap modal not updating with vue js v2 two way binding
I'm new to vue js and trying to use it with a bootstrap modal to view more data. My scenario is a table with multiple records and a button to see in depth details for the clicked record in a bootstrap modal. After clicking the first button it caches and doesn't update it while selecting another button for different details.

Does anyone see what I'm doing wrong?

(It's a combination of Laravel, jQuery and VueJS)

HTML Table:

```<code><table class="table table-striped">
<thead>
    <tr>
        <th>E-mail address</th>
        <th>Status</th>
        <th>Sent at</th>
        <th>Expires in</th>
        <th></th>
    </tr>
</thead>
<tbody>
    <tr>
        <td class="v-align-middle">
            john@doe.example
        </td>
        <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
        </td>
        <td class="v-align-middle">
            2017-06-05 17:59:15
        </td>
        <td class="v-align-middle">
            29 days
        </td>
        <td>
            <div class="btn-group pull-right">
                <a href="#" class="btn btn-default" data-toggle="modal" data-target="#inviteDetailsModal" data-email="john@doe.example">
                    <i class="fa fa-eye"></i>
                </a>
            </div>
        </td>
    </tr>
    <tr>
        <td class="v-align-middle">
            jane@doe.example
        </td>
        <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
        </td>
        <td class="v-align-middle">
            2017-06-05 13:27:25
        </td>
        <td class="v-align-middle">
            29 days
        </td>
        <td>
            <div class="btn-group pull-right">
                <a href="#" class="btn btn-default" data-toggle="modal" data-target="#inviteDetailsModal" data-email="jane@doe.example">
                    <i class="fa fa-eye"></i>
                </a>
            </div>
        </td>
    </tr>
</tbody>
</code>```

JavaScript:

```<code>$('[data-target="#inviteDetailsModal"]').on('click', function () {
    let email = $(this).data('email'),
        baseUrl = $('html').data('base');

    Vue.component('invite-details', {
        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null
            }
        },
        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                this.$http.get(baseUrl + '/system/invites/' + email + '/details')
                    .then(response => {
                        this.update(response.body);
                    }, response => {
                        console.log('whoops something went wrong');
                    });
            }
        },
        mounted: function () {
            this.$el.addEventListener('shown.bs.modal', this.fetchData());
        },
        beforeDestroy: function () {
            this.$el.removeEventListener('shown.bs.modal', this.fetchData());
        }
    });

    new Vue({
        el: '#inviteDetailsModal'
    });
});
</code>```

The bootstrap modal:

```<code><div class="modal fade slide-up" id="inviteDetailsModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content-wrapper">
        <invite-details inline-template>
            <div class="modal-content" id="details">
                <div class="modal-header clearfix text-left">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        <i class="pg-close fs-14"></i>
                    </button>
                    <h5>
                        Invite details for <span class="semi-bold">@{{ email }}</span>
                    </h5>
                    <p class="p-b-10">
                        <span data-tooltip="true" data-placement="bottom" title="token">
                            <em>@{{ token }}</em>
                        </span>
                    </p>
                </div>
                <div class="modal-body">
                    <table class="table table-striped">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>Sent at</th>
                            <th>Status</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="log in logs">
                            <td>@{{ log.number }}</td>
                            <td>@{{ log.sentAt }}</td>
                            <td>@{{ log.status }}</td>
                        </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-footer text-center">
                    <span class="hint-text">
                        <em>expires in <strong>@{{ expires }}</strong> days</em>
                    </span>
                </div>
            </div>
        </invite-details>
    </div>
</div>
</code>```

答:
Alright I dug in deep to get this working and went the extra mile because you mentioned your were new at VueJS. I recognised my old self in your code where you go into VueJS with a JQuery mindset ;-)

First few quick notes before dropping the full code:

Use the table DB row's integer ID to reference the user everywhere.
This way when the email is updated, you still know who it is in the
frontend. By examining the code I saw that the email can change
(because it's an updateable data property, but it's also used in
your GET request: baseUrl + '/system/invites/' + email +
'/details'

Subsequently, you can use this ID to easily generate unique instances
of your modal :-) This is the way you want to be working with VueJS!

Since you're using the same data in multiple places, have a look at
Vuex for a store. It may look daunting at first but it's great once
you get to grips with it. In your case, the same dataset would be
used for the original table and the modals. If one updates,
everything updates!

With Vuex you can trigger updates from anywhere. Right now the data
gets updated every time the eye button is clicked. However, this is
pretty hacky as I've made the button part of the modal's template,
and every time it gets clicked it calls fetchData() (check the
console). What you want to do ideally is use Vuex and generate
everything from the single point of truth dataset. Currently, if the
modal's data is updated, the original table is not.

With VueJS it's just as easy to create your own modal. The upside of
this is less overhead in your code, as you can use v-if, so it
won't be loaded into the DOM unless actually required. And judging
from your current code, the details button would be clicked
occasionally.

Install VueJS debugger if you haven't already:
https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd,
it will help you 'see' under the hood.

Alright so now for the code! First, add this line to your app.js file:

```<code>import JaimyTable from './components/stackoverflow/JaimyTable.vue'
</code>```

Right above the var app = new Vue({ line. And add it to your components, so you end up with something like this:

```<code>import JaimyTable from './components/stackoverflow/JaimyTable.vue'

var app = new Vue({

    components: {
        JaimyTable,
    },

});
</code>```

Here's the JaimyTable.vue file:

```<code><template>
    <div class="container">
        <table class="table table-striped">
            <thead>
            <tr>
                <th>E-mail address</th>
                <th>Status</th>
                <th>Sent at</th>
                <th>Expires in</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td class="v-align-middle">
                    john@doe.example
                </td>
                <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
                </td>
                <td class="v-align-middle">
                    2017-06-05 17:59:15
                </td>
                <td class="v-align-middle">
                    29 days
                </td>
                <td>
                    <div class="btn-group pull-right">

                        <jaimy-modal id="1"></jaimy-modal>

                    </div>
                </td>
            </tr>
            <tr>
                <td class="v-align-middle">
                    jane@doe.example
                </td>
                <td class="v-align-middle">
                <span class="label label-default">
                    pending
                </span>
                </td>
                <td class="v-align-middle">
                    2017-06-05 13:27:25
                </td>
                <td class="v-align-middle">
                    29 days
                </td>
                <td>
                    <div class="btn-group pull-right">

                        <jaimy-modal id="2"></jaimy-modal>

                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    import JaimyModal from './JaimyModal.vue'

    export default {

        components: { JaimyModal },

        props: [],

        mixins: [],

        data: function () {
            return {
                //
            }
        },

        computed: {
            computed_variable() {
                return '';
            }
        },

        created() {
            //
        },

        mounted() {
            //
        },

        methods: {
            //
        },

        watch: {
            //
        }
    }
</script>
</code>```

And please note the <jaimy-modal id="1"></jaimy-modal> lines. You probably want to use v-for to generate the all the
 rows automatically :) Make sure the id= corresponds to the ID in your database.

Now for the JaimyModal.vue where all the magic happens:

```<code><template>
    <div>
        <a href="#" class="btn btn-default" data-toggle="modal" :data-target="'#inviteDetailsModal' + id" @click="fetchData()">
            <i class="fa fa-eye"></i>
        </a>

        <div class="modal fade slide-up" :id="'inviteDetailsModal' + id" tabindex="-1" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content-wrapper">

                    <div class="modal-content" id="details">
                        <div class="modal-header clearfix text-left">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                <i class="pg-close fs-14"></i>
                            </button>
                            <h5>
                                Invite details for <span class="semi-bold">{{ email }}</span>
                            </h5>
                            <p class="p-b-10">
                        <span data-tooltip="true" data-placement="bottom" title="token">
                            <em>{{ token }}</em>
                        </span>
                            </p>
                        </div>
                        <div class="modal-body">
                            <table class="table table-striped">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Sent at</th>
                                    <th>Status</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr v-for="log in logs">
                                    <td>{{ log.number }}</td>
                                    <td>{{ log.sentAt }}</td>
                                    <td>{{ log.status }}</td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="modal-footer text-center">
                            <span class="hint-text">
                                <em>expires in <strong>{{ expires }}</strong> days</em>
                            </span>
                        </div>
                    </div>

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

<script>
    export default {

        props: ['id'],

        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null,
                baseUrl: 'https://yourbaseurl.com',
            }
        },

        mounted: function () {
            //
        },

        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                console.log('data fetched');

                // Commented out for local purposes
//                this.$http.get(this.baseUrl + '/system/invites/' + this.email + '/details')
//                        .then(response => {
//                            this.update(response.body);
//                        }, response => {
//                            console.log('whoops something went wrong');
//                        });

                // Dummy data
                this.update({
                    email: 'test@test ' + this.id + '.com',
                    token: 'token123123asdsasdasdasd',
                    logs: [
                        {
                            number: 1,
                            sentAt: '2017-01-01',
                            status: 'Ok',
                        },
                        {
                            number: 2,
                            sentAt: '2017-02-01',
                            status: 'Failed',
                        },
                    ],
                    expires: '2017-10-01'
                });
            }
        },

    }
</script>
</code>```

Important to note here is the :data-target="'#inviteDetailsModal' + id" part in the button, where the number corresponds to the id of the prop. By using the : you're making it an expression, and it resolves to a unique reference.

As you can see the setup is completely different than you had before. Where the modal is a nested component of your table row. Once you start thinking of Components as recurring parts of look and functionality, but with unique data within it, things will click fast. Think of it as Model in Laravel.

After a long time of being told that you need to separate design (CSS), mark-up (HTML) and functionality (JS), it's weird to have it all sitting there in 1 file. But embrace it, and you'll fall in love with VueJS :D

And give Vuex a look! The second you get multiple components that use and manipulate the same dataset, it's a god-send!

Ow and finally: the second you start thinking of using things like fn.trigger and whatnot, you're approaching VueJS wrong. Keep that in mind :) It has all the tools necessary for you to work with the page, and then some!

Happy coding!

Body:
I'm new to vue js and trying to use it with a bootstrap modal to view more data. My scenario is a table with multiple records and a button to see in depth details for the clicked record in a bootstrap modal. After clicking the first button it caches and doesn't update it while selecting another button for different details.

Does anyone see what I'm doing wrong?

(It's a combination of Laravel, jQuery and VueJS)

HTML Table:

        E-mail address
        Status
        Sent at
        Expires in

            john@doe.example

                pending

            2017-06-05 17:59:15

            29 days

            jane@doe.example

                pending

            2017-06-05 13:27:25

            29 days

JavaScript:

$('[data-target="#inviteDetailsModal"]').on('click', function () {
    let email = $(this).data('email'),
        baseUrl = $('html').data('base');

    Vue.component('invite-details', {
        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null
            }
        },
        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                this.$http.get(baseUrl + '/system/invites/' + email + '/details')
                    .then(response => {
                        this.update(response.body);
                    }, response => {
                        console.log('whoops something went wrong');
                    });
            }
        },
        mounted: function () {
            this.$el.addEventListener('shown.bs.modal', this.fetchData());
        },
        beforeDestroy: function () {
            this.$el.removeEventListener('shown.bs.modal', this.fetchData());
        }
    });

    new Vue({
        el: '#inviteDetailsModal'
    });
});

The bootstrap modal:

        <invite-details inline-template>

                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">

                    </button>

                        Invite details for @{{ email }}

                            @{{ token }}

                            #
                            Sent at
                            Status

                            @{{ log.number }}
                            @{{ log.sentAt }}
                            @{{ log.status }}

                        expires in @{{ expires }} days

        </invite-details>

Body:
Alright I dug in deep to get this working and went the extra mile because you mentioned your were new at VueJS. I recognised my old self in your code where you go into VueJS with a JQuery mindset ;-)

First few quick notes before dropping the full code:

Use the table DB row's integer ID to reference the user everywhere.
This way when the email is updated, you still know who it is in the
frontend. By examining the code I saw that the email can change
(because it's an updateable data property, but it's also used in
your GET request: baseUrl + '/system/invites/' + email +
'/details'

Subsequently, you can use this ID to easily generate unique instances
of your modal :-) This is the way you want to be working with VueJS!

Since you're using the same data in multiple places, have a look at
Vuex for a store. It may look daunting at first but it's great once
you get to grips with it. In your case, the same dataset would be
used for the original table and the modals. If one updates,
everything updates!

With Vuex you can trigger updates from anywhere. Right now the data
gets updated every time the eye button is clicked. However, this is
pretty hacky as I've made the button part of the modal's template,
and every time it gets clicked it calls fetchData() (check the
console). What you want to do ideally is use Vuex and generate
everything from the single point of truth dataset. Currently, if the
modal's data is updated, the original table is not.

With VueJS it's just as easy to create your own modal. The upside of
this is less overhead in your code, as you can use v-if, so it
won't be loaded into the DOM unless actually required. And judging
from your current code, the details button would be clicked
occasionally.

Install VueJS debugger if you haven't already:
https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd,
it will help you 'see' under the hood.

Alright so now for the code! First, add this line to your app.js file:

import JaimyTable from './components/stackoverflow/JaimyTable.vue'

Right above the var app = new Vue({ line. And add it to your components, so you end up with something like this:

import JaimyTable from './components/stackoverflow/JaimyTable.vue'

var app = new Vue({

    components: {
        JaimyTable,
    },

});

Here's the JaimyTable.vue file:

<template>
    <div class="container">
        <table class="table table-striped">
            <thead>
            <tr>
                <th>E-mail address</th>
                <th>Status</th>
                <th>Sent at</th>
                <th>Expires in</th>
                <th></th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td class="v-align-middle">
                    john@doe.example
                </td>
                <td class="v-align-middle">
            <span class="label label-default">
                pending
            </span>
                </td>
                <td class="v-align-middle">
                    2017-06-05 17:59:15
                </td>
                <td class="v-align-middle">
                    29 days
                </td>
                <td>
                    <div class="btn-group pull-right">

                        <jaimy-modal id="1"></jaimy-modal>

                    </div>
                </td>
            </tr>
            <tr>
                <td class="v-align-middle">
                    jane@doe.example
                </td>
                <td class="v-align-middle">
                <span class="label label-default">
                    pending
                </span>
                </td>
                <td class="v-align-middle">
                    2017-06-05 13:27:25
                </td>
                <td class="v-align-middle">
                    29 days
                </td>
                <td>
                    <div class="btn-group pull-right">

                        <jaimy-modal id="2"></jaimy-modal>

                    </div>
                </td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script>
    import JaimyModal from './JaimyModal.vue'

    export default {

        components: { JaimyModal },

        props: [],

        mixins: [],

        data: function () {
            return {
                //
            }
        },

        computed: {
            computed_variable() {
                return '';
            }
        },

        created() {
            //
        },

        mounted() {
            //
        },

        methods: {
            //
        },

        watch: {
            //
        }
    }
</script>

And please note the <jaimy-modal id="1"></jaimy-modal> lines. You probably want to use v-for to generate the all the <tr> rows automatically :) Make sure the id= corresponds to the ID in your database.

Now for the JaimyModal.vue where all the magic happens:

<template>
    <div>
        <a href="#" class="btn btn-default" data-toggle="modal" :data-target="'#inviteDetailsModal' + id" @click="fetchData()">
            <i class="fa fa-eye"></i>
        </a>

        <div class="modal fade slide-up" :id="'inviteDetailsModal' + id" tabindex="-1" role="dialog">
            <div class="modal-dialog">
                <div class="modal-content-wrapper">

                    <div class="modal-content" id="details">
                        <div class="modal-header clearfix text-left">
                            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                                <i class="pg-close fs-14"></i>
                            </button>
                            <h5>
                                Invite details for <span class="semi-bold">{{ email }}</span>
                            </h5>
                            <p class="p-b-10">
                        <span data-tooltip="true" data-placement="bottom" title="token">
                            <em>{{ token }}</em>
                        </span>
                            </p>
                        </div>
                        <div class="modal-body">
                            <table class="table table-striped">
                                <thead>
                                <tr>
                                    <th>#</th>
                                    <th>Sent at</th>
                                    <th>Status</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr v-for="log in logs">
                                    <td>{{ log.number }}</td>
                                    <td>{{ log.sentAt }}</td>
                                    <td>{{ log.status }}</td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                        <div class="modal-footer text-center">
                            <span class="hint-text">
                                <em>expires in <strong>{{ expires }}</strong> days</em>
                            </span>
                        </div>
                    </div>

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

<script>
    export default {

        props: ['id'],

        data: function () {
            return {
                email: null,
                token: null,
                logs: [],
                expires: null,
                baseUrl: 'https://yourbaseurl.com',
            }
        },

        mounted: function () {
            //
        },

        methods: {
            update: function (data) {
                this.email = data['email'];
                this.token = data['token'];
                this.logs = data['logs'];
                this.expires = data['expires'];
            },
            fetchData: function () {
                console.log('data fetched');

                // Commented out for local purposes
//                this.$http.get(this.baseUrl + '/system/invites/' + this.email + '/details')
//                        .then(response => {
//                            this.update(response.body);
//                        }, response => {
//                            console.log('whoops something went wrong');
//                        });

                // Dummy data
                this.update({
                    email: 'test@test ' + this.id + '.com',
                    token: 'token123123asdsasdasdasd',
                    logs: [
                        {
                            number: 1,
                            sentAt: '2017-01-01',
                            status: 'Ok',
                        },
                        {
                            number: 2,
                            sentAt: '2017-02-01',
                            status: 'Failed',
                        },
                    ],
                    expires: '2017-10-01'
                });
            }
        },

    }
</script>

Important to note here is the :data-target="'#inviteDetailsModal' + id" part in the button, where the number corresponds to the id of the prop. By using the : you're making it an expression, and it resolves to a unique reference.

As you can see the setup is completely different than you had before. Where the modal is a nested component of your table row. Once you start thinking of Components as recurring parts of look and functionality, but with unique data within it, things will click fast. Think of it as Model in Laravel.

After a long time of being told that you need to separate design (CSS), mark-up (HTML) and functionality (JS), it's weird to have it all sitting there in 1 file. But embrace it, and you'll fall in love with VueJS :D

And give Vuex a look! The second you get multiple components that use and manipulate the same dataset, it's a god-send!

Ow and finally: the second you start thinking of using things like fn.trigger and whatnot, you're approaching VueJS wrong. Keep that in mind :) It has all the tools necessary for you to work with the page, and then some!

Happy coding!


来源: stackexchange

问:
Round NaN in Haskell
To my great surprise, I found that rounding a NaN value in Haskell returns a gigantic negative number:

```<code>round (0/0)
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824
</code>```

The same thing happens with floor and ceiling.

What is happening here? Is this behavior intended? Of course, I understand that anyone who doesn't want this behavior can always write another function that checks isNaN - but are there existing alternative standard library functions that handle NaN more sanely (for some definition of "more sanely")?

答:
TL;DR: NaN have an arbitrary representation between 2 ^ 1024 and 2 ^ 1025 (bounds not included), and - 1.5 * 2 ^ 1024 (which is one possible) NaN happens to be the one you hit.

Why any reasoning is off

What is happening here?

You're entering the region of undefined behaviour. Or at least that is what you would call it in some other languages. The report defines round as follows:

 6.4.6 Coercions and Component Extraction

The ceiling, floor, truncate, and round functions each take a real fractional argument and return an integral result. … round x returns the nearest integer to x, the even integer if x is equidistant between two integers.

In our case x does not represent a number to begin with. According to 6.4.6, y = round x should fulfil that any other z from round's codomain has an equal or greater distance:

```<code>y = round x ⇒ ∀z : dist(z,x) >= dist(y,x)
</code>```

However, the distance (aka the subtraction) of numbers is defined only for, well, numbers. If we used

```<code>dist n d = fromIntegral n - d
</code>```

we get in trouble soon: any operation that includes NaN will return NaN again, and comparisons on NaN fail, so our property above does not hold for any z if x was a NaN to begin with. If we check for NaN, we can return any value, but then our property holds for all pairs:

```<code>dist n d = if isNaN d then constant else fromIntegral n - d
</code>```

So we're completely arbitrary in what round x shall return if x was not a number.

Why do we get that large number regardless?

"OK", I hear you say, "that's all fine and dandy, but why do I get that number?" That's a good question.

Is this behavior intended?

Somewhat. It isn't really intended, but to be expected. First of all, we have to know how Double works.

IEE 754 double precision floating point numbers

A Double in Haskell is usually a IEEE 754 compliant double precision floating point number, that is a number that has 64 bits and is represented with

```<code>x = s * m * (b ^ e)
</code>```

where s is a single bit, m is the mantissa (52 bits) and e is the exponent (11 bits, floatRange). b is the base, and its usually 2 (you can check with floadRadix). Since the value of m is normalized, every well-formed Double has a unique representation.

IEEE 754 NaN

Except NaN. NaN is represented as the emax+1, as well as a non-zero mantissa. So if the bitfield

```<code>SEEEEEEEEEEEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM
</code>```

represents a Double, what's a valid way to represent NaN?

```<code>?111111111111000000000000000000000000000000000000000000000000000
            ^
</code>```

That is, a single M is set to 1, the other are not necessary to set this notion. The sign is arbitrary. Why only a single bit? Because its sufficient.

Interpret NaN as Double

Now, when we ignore the fact that this is a malformed Double—a NaN– and really, really, really want to interpret it as number, what number would we get?

```<code>m = 1.5
e = 1024

x = 1.5 * 2 ^ 1024
  = 3 * 2 ^ 1024 / 2
  = 3 * 2 ^ 1023
</code>```

And lo and behold, that's exactly the number you get for round (0/0):

```<code>ghci> round $ 0 / 0
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824
ghci> negate $ 3 * 2 ^ 1023
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824
</code>```

Which brings our small adventure to a halt. We have a NaN, which yields a 2 ^ 1024, and we have some non-zero mantissa, which yields a result with absolute value between 2 ^ 1024 < x < 2 ^ 1025.

Note that this isn't the only way NaN can get represented:

In IEEE 754, NaNs are often represented as floating-point numbers with the exponent emax + 1 and nonzero significands. Implementations are free to put system-dependent information into the significand. Thus there is not a unique NaN, but rather a whole family of NaNs.

For more information, see the classic paper on floating point numbers by Goldberg.

ContentLicense: CC BY-SA 3.0

Title: Round NaN in Haskell

Body:
To my great surprise, I found that rounding a NaN value in Haskell returns a gigantic negative number:

round (0/0)
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824

The same thing happens with floor and ceiling.

What is happening here? Is this behavior intended? Of course, I understand that anyone who doesn't want this behavior can always write another function that checks isNaN - but are there existing alternative standard library functions that handle NaN more sanely (for some definition of "more sanely")?

Body:
TL;DR: NaN have an arbitrary representation between 2 ^ 1024 and 2 ^ 1025 (bounds not included), and - 1.5 * 2 ^ 1024 (which is one possible) NaN happens to be the one you hit.

Why any reasoning is off

What is happening here?

You're entering the region of undefined behaviour. Or at least that is what you would call it in some other languages. The report defines round as follows:

 6.4.6 Coercions and Component Extraction

The ceiling, floor, truncate, and round functions each take a real fractional argument and return an integral result. … round x returns the nearest integer to x, the even integer if x is equidistant between two integers.

In our case x does not represent a number to begin with. According to 6.4.6, y = round x should fulfil that any other z from round's codomain has an equal or greater distance:

y = round x ⇒ ∀z : dist(z,x) >= dist(y,x)

However, the distance (aka the subtraction) of numbers is defined only for, well, numbers. If we used

dist n d = fromIntegral n - d

we get in trouble soon: any operation that includes NaN will return NaN again, and comparisons on NaN fail, so our property above does not hold for any z if x was a NaN to begin with. If we check for NaN, we can return any value, but then our property holds for all pairs:

dist n d = if isNaN d then constant else fromIntegral n - d

So we're completely arbitrary in what round x shall return if x was not a number.

Why do we get that large number regardless?

"OK", I hear you say, "that's all fine and dandy, but why do I get that number?" That's a good question.

Is this behavior intended?

Somewhat. It isn't really intended, but to be expected. First of all, we have to know how Double works.

IEE 754 double precision floating point numbers

A Double in Haskell is usually a IEEE 754 compliant double precision floating point number, that is a number that has 64 bits and is represented with

x = s * m * (b ^ e)

where s is a single bit, m is the mantissa (52 bits) and e is the exponent (11 bits, floatRange). b is the base, and its usually 2 (you can check with floadRadix). Since the value of m is normalized, every well-formed Double has a unique representation.

IEEE 754 NaN

Except NaN. NaN is represented as the emax+1, as well as a non-zero mantissa. So if the bitfield

SEEEEEEEEEEEMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM

represents a Double, what's a valid way to represent NaN?

?111111111111000000000000000000000000000000000000000000000000000
            ^

That is, a single M is set to 1, the other are not necessary to set this notion. The sign is arbitrary. Why only a single bit? Because its sufficient.

Interpret NaN as Double

Now, when we ignore the fact that this is a malformed Double—a NaN– and really, really, really want to interpret it as number, what number would we get?

m = 1.5
e = 1024

x = 1.5 * 2 ^ 1024
  = 3 * 2 ^ 1024 / 2
  = 3 * 2 ^ 1023

And lo and behold, that's exactly the number you get for round (0/0):

ghci> round $ 0 / 0
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824
ghci> negate $ 3 * 2 ^ 1023
-269653970229347386159395778618353710042696546841345985910145121736599013708251444699062715983611304031680170819807090036488184653221624933739271145959211186566651840137298227914453329401869141179179624428127508653257226023513694322210869665811240855745025766026879447359920868907719574457253034494436336205824

Which brings our small adventure to a halt. We have a NaN, which yields a 2 ^ 1024, and we have some non-zero mantissa, which yields a result with absolute value between 2 ^ 1024 < x < 2 ^ 1025.

Note that this isn't the only way NaN can get represented:

In IEEE 754, NaNs are often represented as floating-point numbers with the exponent emax + 1 and nonzero significands. Implementations are free to put system-dependent information into the significand. Thus there is not a unique NaN, but rather a whole family of NaNs.

For more information, see the classic paper on floating point numbers by Goldberg.


问:
How to execute stored procedures by Order in SQL Server
I have created a stored procedure which calls other stored procedures but I don't want to execute them at the same time. Stored procedure #1 execution takes time so when it finishes stored procedure #2 will start to execute.

How can I do this?

```<code>EXEC SP1;
--wait for SP1 to finish its job
EXEC SP2;
</code>```

Any suggestions?

答:
Try using something like : </p>

```<code>BEGIN TRY
BEGIN TRANSACTION
exec( @sp1)
exec(@sp2)
exec(@sp3)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 (Validate it )
ROLLBACK (rollback to sp where you want to )
END CATCH
</code>```

Body:
I have created a stored procedure which calls other stored procedures but I don't want to execute them at the same time. Stored procedure #1 execution takes time so when it finishes stored procedure #2 will start to execute.

How can I do this?

EXEC SP1;
--wait for SP1 to finish its job
EXEC SP2;

Any suggestions?

Body:
Try using something like :

BEGIN TRY
BEGIN TRANSACTION
exec( @sp1)
exec(@sp2)
exec(@sp3)
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0 (Validate it )
ROLLBACK (rollback to sp where you want to )
END CATCH


问:
MVC in Visual Studio Express
I got Visual Studio 2010 Express C# Edition. I'm using WinXP as OS.

How do I get ASP.Net MVC in it? I saw another question that stated that MVC was included automatically, but I cannot find it anywhere. I've also tried by installing MVC3 RC2. Didn't show up either.

Isn't it possible to use MVC with Express edition?

(I've also got VS 2008 Professional on the same computer)

Edit

I needed the Visual Studio Web Developer Edition to get MVC2.

But how do I get MVC3?

Edit 2

I have XP Home edition which is not supported by web platform installer since IIS is not included. I guess that's why MVC3 wont install in Visual Studio 2010 Express (although it installed fine on my computer which is a bit strange)

答:
Isn't it possible to use MVC with Express edition?

Sure is. I installed VS2010 web express edition and when I choose New Project then it shows the MVC2 web application and empty web application project template. Last week I also installed MVC3 RC via the web platform installer and that shows up too.

ContentLicense: CC BY-SA 2.5

Title: MVC in Visual Studio Express


问:
execute xml to html transformation with xslt in groovy
I want to transform my xml file to html. The xslt code is working but I dont know how to perform the transformation in my groovy script. I tried:

```<code>    import javax.xml.transform.TransformerFactory
    import javax.xml.transform.stream.StreamResult
    import javax.xml.transform.stream.StreamSource
    import javax.xml.transform.Templates

stage('make Changelog'){
    node('fetch'){
       dir('C:\\Jenkins_Slave_FETCH\\xsl_changelog') {

            def xslt= readFile("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\convert.xsl")

            def transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(xslt)))

            def xml= readFile("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\tmp.xml")

            def html = new FileOutputStream("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\Changelog.html")

            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(html))
        }
    }
}
</code>```

But this Code results in the following error:

```<code>[Pipeline] stage
[Pipeline] { (make Changelog)
[Pipeline] node
Running on DEGTW6216_Slave_FETCH in C:\Jenkins_Slave_FETCH\workspace\Gen7000\test
[Pipeline] {
[Pipeline] dir
Running in C:\Jenkins_Slave_FETCH\xsl_changelog
[Pipeline] {
[Pipeline] readFile
[Pipeline] readFile
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
an exception which occurred:
    in field locals
    in field caller
    in field e
    in field program
    in field thread
    in field body
    in field step
    in field thread
    in field this$0
    in field returnAddress
    in field parent
    in field caller
    in field parent
    in field parent
    in field capture
    in field def
    in field closures
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@30b1d3
Caused: java.io.NotSerializableException: com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at java.util.HashMap.internalWriteEntries(Unknown Source)
    at java.util.HashMap.writeObject(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at java.util.HashMap.internalWriteEntries(Unknown Source)
    at java.util.HashMap.writeObject(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:140)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:458)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:434)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:422)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:362)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:82)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:242)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:230)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Finished: FAILURE
</code>```

Does somebody know how to resolve this?

答: I solved the issue. It seems that the jenkins security settings are not OK with xsl transformations in groovy. So I perform the tranformation in powershell and everything works fine.</p>

Body:
I want to transform my xml file to html. The xslt code is working but I dont know how to perform the transformation in my groovy script. I tried:

    import javax.xml.transform.TransformerFactory
    import javax.xml.transform.stream.StreamResult
    import javax.xml.transform.stream.StreamSource
    import javax.xml.transform.Templates

stage('make Changelog'){
    node('fetch'){
       dir('C:\\Jenkins_Slave_FETCH\\xsl_changelog') {

            def xslt= readFile("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\convert.xsl")

            def transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(xslt)))

            def xml= readFile("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\tmp.xml")

            def html = new FileOutputStream("C:\\Jenkins_Slave_FETCH\\xsl_changelog\\Changelog.html")

            transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(html))
        }
    }
}

But this Code results in the following error:

[Pipeline] stage
[Pipeline] { (make Changelog)
[Pipeline] node
Running on DEGTW6216_Slave_FETCH in C:\Jenkins_Slave_FETCH\workspace\Gen7000\test
[Pipeline] {
[Pipeline] dir
Running in C:\Jenkins_Slave_FETCH\xsl_changelog
[Pipeline] {
[Pipeline] readFile
[Pipeline] readFile
[Pipeline] }
[Pipeline] // dir
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
an exception which occurred:
    in field locals
    in field caller
    in field e
    in field program
    in field thread
    in field body
    in field step
    in field thread
    in field this$0
    in field returnAddress
    in field parent
    in field caller
    in field parent
    in field parent
    in field capture
    in field def
    in field closures
    in object org.jenkinsci.plugins.workflow.cps.CpsThreadGroup@30b1d3
Caused: java.io.NotSerializableException: com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:860)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at java.util.HashMap.internalWriteEntries(Unknown Source)
    at java.util.HashMap.writeObject(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:967)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.BlockMarshaller.doWriteObject(BlockMarshaller.java:65)
    at org.jboss.marshalling.river.BlockMarshaller.writeObject(BlockMarshaller.java:56)
    at org.jboss.marshalling.MarshallerObjectOutputStream.writeObjectOverride(MarshallerObjectOutputStream.java:50)
    at org.jboss.marshalling.river.RiverObjectOutputStream.writeObjectOverride(RiverObjectOutputStream.java:179)
    at java.io.ObjectOutputStream.writeObject(Unknown Source)
    at java.util.HashMap.internalWriteEntries(Unknown Source)
    at java.util.HashMap.writeObject(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor124.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.jboss.marshalling.reflect.SerializableClass.callWriteObject(SerializableClass.java:271)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:976)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteFields(RiverMarshaller.java:1032)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteSerializableObject(RiverMarshaller.java:988)
    at org.jboss.marshalling.river.RiverMarshaller.doWriteObject(RiverMarshaller.java:854)
    at org.jboss.marshalling.AbstractObjectOutput.writeObject(AbstractObjectOutput.java:58)
    at org.jboss.marshalling.AbstractMarshaller.writeObject(AbstractMarshaller.java:111)
    at org.jenkinsci.plugins.workflow.support.pickles.serialization.RiverWriter.writeObject(RiverWriter.java:140)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:458)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgram(CpsThreadGroup.java:434)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.saveProgramIfPossible(CpsThreadGroup.java:422)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:362)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:82)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:242)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:230)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
Finished: FAILURE

Does somebody know how to resolve this?


问:
Moving Files into a Real Folder in Xcode
When I started my project I was happy to use Groups in Xcode rather than literal folders: Since I'm using the browser in Xcode to access everything, stuff was nicely organized and I was happy.

However, now that the project is about to be shared for version control, the project folder itself is a horror show for those trying to scan it via a terminal, about 300 files, over half of which are graphics.

I'm trying to now reorganize things, creating real folders and importing them into Xcode. Unfortunately Xcode doesn't let me work with them the way it does with groups. For example, if I right-click on an actual added folder (blue, not yellow) and choose to add existing files, it doesn't actually put them in that folder, it puts them in its root.

Similarly, I can't move a file from a faux-folder (a group) into a real folder: Xcode doesn't consider the real folders to be valid places to move stuff to.

What am I missing? How can I convince Xcode to let me use the folders the way I use groups? There's an answer here to a somewhat similar question, but it doesn't actually solve my problem since I'm working with existing files.

答:
Xcode 9

It seems Xcode 9 now supports it by default. When you move files from a group to another, the file will also be moved from the old folder to the new folder. This was announced in WWDC 2017.


问:
Terminating connection because of crash of another server process -Postgres
Everytime i run the same query i'm getting this error:

DETAIL:  The postmaster has commanded this server process to roll back the current transaction and exit, because another server process exited abnormally and possibly corrupted shared memory.
HINT:  In a moment you should be able to reconnect to the database and repeat your command.
server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.
connection to server was lost

I'm using phpPgAdmin 5.1.

答:
A concurrent query in a different database session has crashed its server backend process. As a consequence, the whole database stops and performs crash recovery from the latest checkpoint.

You should look into the database server log to see what the problem is.


问:
JQuery event binding getting overriden
I'm trying to bind events to entities inside a certain for loop inside a for loop.

Basically it's a for loop inside a for loop and the methods do bind. But my problem is that when ever I interact with the inner loop implemented method first, then the outer loop implemented method, then only the outer loop implemented method would work and the inner level implemented method will not work anymore.

Same happens if I start interacting with the outer loop implemented method where only that method would work and the inner loop implemented method will not work at all. This is what I have tried so far:

```<code>var tree = document.getElementById('tree');

for (var i in result) {
  if (result[i].children) {
    // fill outer layer entities with children
    tree.innerHTML +=
      '<div id="layer_one_title_' + [i] + '" class="title">' +
      '<i class="dropdown icon"></i>' +
      '<i class="folder icon"></i>' + result[i].text +
      '<i class="plus icon lev_one_add" ></i>' +
      '</div>' +
      '<div id="layer_one_content_' + [i] + '" class="content active"></div>';

    $('#layer_one_title_' + [i]).on('click', '.lev_one_add', function(event) {
      newFirstNode(result[i], event);
    });

    let layer_one_content = document.getElementById('layer_one_content_' + [i]);
    for (var j in result[i].children) {
      if (result[i].children[j].children) {
        // fill inner layer entities with children
        layer_one_content.innerHTML +=
          '<div id="layer_one_' + [i] + '_' + [j] + '" class="accordion layer_one">' +
          '<div id="layer_two_title_' + [i] + '_' + [j] + '" class="title">' +
          '<i class="dropdown icon"></i>' +
          '<i class="folder icon"></i>' + result[i].children[j].text +
          '<i class="plus icon lev_two_add"></i>' +
          '</div>' +
          '<div id="layer_two_content_' + [i] + '_' + [j] + '" class="content active"></div>' +
          '</div>';

        $('#layer_two_title_' + [i] + '_' + [j]).on('click', '.lev_two_add', function(event) {
          newFirstNode(result[i], event);
        });
</code>```

Any idea what I'm doing wrong here?

答:
I'm assuming that you're using jQuery here. See if the code below works out for you. (Altered your code).

Btw, didn't test this code. Hope it works :P

```<code>// Note: Trying my best to prevent binding events and injecting html within a loop.

// Find the parent element first.
let $tree = $("#tree");

// Bind a delegate event on to the parent for a child click.
$tree.on('click', ".lev_one_add", result, function (event) {
    let $self = $(this);
    let result = event.data; // Access the data passed when binding this event (third param in this event statement).
    let index = $self.data("index"); // Access the index which was set as an attribute in the html format ("data-index").

    newFirstNode(result[index], event);
});

$tree.on('click', '.layer_two_container .lev_two_add', result, function (event) {
    let $self = $(this);
    let result = event.data; // Access the data passed when binding this event (third param in this event statement).
    let parentIndex = $self.data("pindex"); // Access the index which was set as an attribute in the html format ("data-pindex").
    let index = $self.data("index"); // Access the index which was set as an attribute in the html format ("data-index").

    if (result[parentIndex] && result[parentIndex].children[index]) {
        newSecondNode(result[parentIndex], event);
    }
});

let htmlChilds = "";
for (var i in result) {
    if (result[i].children) {
        // Append the html as a string all at once instead of injecting each html child at a time.
        // (This way is performance efficient)
        htmlChilds +=
            '<div id="layer_one_title_' + [i] + '" class="title">' +
            '<i class="dropdown icon"></i>' +
            '<i class="folder icon"></i>' + result[i].text +

            // Added an attribute "data-index" to hold the index.
            '<i class="plus icon lev_one_add" data-index="' + [i] + '" ></i>' +
            '</div>' +

            // Open the .layer_two_container div.
            '<div id="layer_one_content_' + [i] + '" class="content active layer_two_container">';

        for (var j in result[i].children) {
            if (result[i].children[j].children) {
                htmlChilds +=
                    '<div id="layer_one_' + [i] + '_' + [j] + '" class="accordion layer_one">' +
                    '<div id="layer_two_title_' + [i] + '_' + [j] + '" class="title">' +
                    '<i class="dropdown icon"></i>' +
                    '<i class="folder icon"></i>' + result[i].children[j].text +

                    // Added attributes "data-pindex" and "data-index" to hold indexes of parent and child.
                    '<i class="plus icon lev_two_add" data-pindex="' + [i] + '" data-index="' + [j] + '"></i>' +
                    '</div>' +
                    '<div id="layer_two_content_' + [i] + '_' + [j] + '" class="content active"></div>' +
                    '</div>';
            }
        }

        // Close the .layer_two_container div.
        htmlChilds += '</div>';
    }
}

// Inject the children html into the parent node.
$tree.html(htmlChilds);
</code>```

Title: JQuery event binding getting overriden

Body:
I'm trying to bind events to entities inside a certain for loop inside a for loop.

Basically it's a for loop inside a for loop and the methods do bind. But my problem is that when ever I interact with the inner loop implemented method first, then the outer loop implemented method, then only the outer loop implemented method would work and the inner level implemented method will not work anymore.

Same happens if I start interacting with the outer loop implemented method where only that method would work and the inner loop implemented method will not work at all. This is what I have tried so far:

var tree = document.getElementById('tree');

for (var i in result) {
  if (result[i].children) {
    // fill outer layer entities with children
    tree.innerHTML +=
      '
' +
      '' +
      '' + result[i].text +
      '' +
      '
' +
      '

';

    $('#layer_one_title_' + [i]).on('click', '.lev_one_add', function(event) {
      newFirstNode(result[i], event);
    });

    let layer_one_content = document.getElementById('layer_one_content_' + [i]);
    for (var j in result[i].children) {
      if (result[i].children[j].children) {
        // fill inner layer entities with children
        layer_one_content.innerHTML +=
          '
' +
          '
' +
          '' +
          '' + result[i].children[j].text +
          '' +
          '
' +
          '

' +
          '
';

        $('#layer_two_title_' + [i] + '_' + [j]).on('click', '.lev_two_add', function(event) {
          newFirstNode(result[i], event);
        });

Any idea what I'm doing wrong here?

Body:
I'm assuming that you're using jQuery here. See if the code below works out for you. (Altered your code).

Btw, didn't test this code. Hope it works :P

// Note: Trying my best to prevent binding events and injecting html within a loop.

// Find the parent element first.
let $tree = $("#tree");

// Bind a delegate event on to the parent for a child click.
$tree.on('click', ".lev_one_add", result, function (event) {
    let $self = $(this);
    let result = event.data; // Access the data passed when binding this event (third param in this event statement).
    let index = $self.data("index"); // Access the index which was set as an attribute in the html format ("data-index").

    newFirstNode(result[index], event);
});

$tree.on('click', '.layer_two_container .lev_two_add', result, function (event) {
    let $self = $(this);
    let result = event.data; // Access the data passed when binding this event (third param in this event statement).
    let parentIndex = $self.data("pindex"); // Access the index which was set as an attribute in the html format ("data-pindex").
    let index = $self.data("index"); // Access the index which was set as an attribute in the html format ("data-index").

    if (result[parentIndex] && result[parentIndex].children[index]) {
        newSecondNode(result[parentIndex], event);
    }
});

let htmlChilds = "";
for (var i in result) {
    if (result[i].children) {
        // Append the html as a string all at once instead of injecting each html child at a time.
        // (This way is performance efficient)
        htmlChilds +=
            '<div id="layer_one_title_' + [i] + '" class="title">' +
            '<i class="dropdown icon"></i>' +
            '<i class="folder icon"></i>' + result[i].text +

            // Added an attribute "data-index" to hold the index.
            '<i class="plus icon lev_one_add" data-index="' + [i] + '" ></i>' +
            '</div>' +

            // Open the .layer_two_container div.
            '<div id="layer_one_content_' + [i] + '" class="content active layer_two_container">';

        for (var j in result[i].children) {
            if (result[i].children[j].children) {
                htmlChilds +=
                    '<div id="layer_one_' + [i] + '_' + [j] + '" class="accordion layer_one">' +
                    '<div id="layer_two_title_' + [i] + '_' + [j] + '" class="title">' +
                    '<i class="dropdown icon"></i>' +
                    '<i class="folder icon"></i>' + result[i].children[j].text +

                    // Added attributes "data-pindex" and "data-index" to hold indexes of parent and child.
                    '<i class="plus icon lev_two_add" data-pindex="' + [i] + '" data-index="' + [j] + '"></i>' +
                    '</div>' +
                    '<div id="layer_two_content_' + [i] + '_' + [j] + '" class="content active"></div>' +
                    '</div>';
            }
        }

        // Close the .layer_two_container div.
        htmlChilds += '</div>';
    }
}

// Inject the children html into the parent node.
$tree.html(htmlChilds);


问:
iOS - How to set image to ImageView according to a specific value
I have several images, and I would like to set the image of my ImageView according to a specific value I get from web service.

For example if I got value "dog" I have to set image of a dog.

All the images are in my xcassets repertory.

Should I make a Switch for that ? Or is there a better way to do it ?

答:
If the web service returns the same names used in your assets then you can just use the returned name directly as the name of the image to use like this:</p>

```<code>let newImage: UIImage? = UIImage(named: imageName) // imageName is the name returned to you by the web service.
self.myUIImageView.image = newImage
</code>```

Body:
If the web service returns the same names used in your assets then you can just use the returned name directly as the name of the image to use like this:

let newImage: UIImage? = UIImage(named: imageName) // imageName is the name returned to you by the web service.
self.myUIImageView.image = newImage


问:
Help optimizing an SQL Query
I am having noticing some performance issues on my MySQL Server. The slow query log is showing four queries which are causing the issue, taking around 10 seconds to run each query. I'm wondering if there is a more efficient way of running the query.

The table I am selecting from has around 13,000 rows, and is structured like:

```<code>id  p   year    time            b      o           type
1   dec 10  2010-12-02 12:34:27 1000    1000        cape
2   jan 10  2010-12-02 12:34:27 1000    1000        cape
3   feb 10  2010-12-02 12:34:27 1000    1000        cape
4   q1  10  2010-12-02 12:34:27 1000    1000        cape
5   q2  10  2010-12-02 12:34:27 1000    1000        cape
6   q3  10  2010-12-02 12:34:27 1000    1000        cape
7   q4  10  2010-12-02 12:34:27 1000    1000        cape
8   11  10  2010-12-02 12:34:27 1000    1000        cape
9   12  10  2010-12-02 12:34:27 1000    1000        cape
10  dec 10  2010-12-02 12:34:27 1000    1000        pmx
11  jan 10  2010-12-02 12:34:27 1000    1000        pmx
12  feb 10  2010-12-02 12:34:27 1000    1000        pmx
13  q1  10  2010-12-02 12:34:27 1000    1000        pmx
14  q2  10  2010-12-02 12:34:27 1000    1000        pmx
15  q3  10  2010-12-02 12:34:27 1000    1000        pmx
16  q4  10  2010-12-02 12:34:27 1000    1000        pmx
</code>```

I run four queries - one for each type, which select each p and order by time. This data is displayed on the front end of the website through four tables.

The queries that are slow are:

```<code>SELECT type,id,p,time,b,o
FROM zz
WHERE id = (SELECT MAX(id) FROM zz AS f
            WHERE f.p = zz.p
            AND type = 'pmx')
AND TYPE = 'pmx';
</code>```

(then the same for three other types)

Does anyone have any tips for improving the actual query?

Thanks

答:
How about something like

```<code>SELECT  zz.type,
        zz.id,
        zz.p,
        zz.time,
        zz.b,
        zz.o
FROM    zz INNER JOIN
        (
            SELECT  type,
                    MAX(id) MaxID
            FROM    zz
            WHERE   type IN ('1','2','3','4')
            GROUP BY type
        ) m ON  zz.type = m.type
            AND zz.ID = m.MaxID
</code>```

Where ('1','2','3','4') are the four types in question.

Title: Help optimizing an SQL Query

Body:
I am having noticing some performance issues on my MySQL Server. The slow query log is showing four queries which are causing the issue, taking around 10 seconds to run each query. I'm wondering if there is a more efficient way of running the query.

The table I am selecting from has around 13,000 rows, and is structured like:

id  p   year    time            b      o           type
1   dec 10  2010-12-02 12:34:27 1000    1000        cape
2   jan 10  2010-12-02 12:34:27 1000    1000        cape
3   feb 10  2010-12-02 12:34:27 1000    1000        cape
4   q1  10  2010-12-02 12:34:27 1000    1000        cape
5   q2  10  2010-12-02 12:34:27 1000    1000        cape
6   q3  10  2010-12-02 12:34:27 1000    1000        cape
7   q4  10  2010-12-02 12:34:27 1000    1000        cape
8   11  10  2010-12-02 12:34:27 1000    1000        cape
9   12  10  2010-12-02 12:34:27 1000    1000        cape
10  dec 10  2010-12-02 12:34:27 1000    1000        pmx
11  jan 10  2010-12-02 12:34:27 1000    1000        pmx
12  feb 10  2010-12-02 12:34:27 1000    1000        pmx
13  q1  10  2010-12-02 12:34:27 1000    1000        pmx
14  q2  10  2010-12-02 12:34:27 1000    1000        pmx
15  q3  10  2010-12-02 12:34:27 1000    1000        pmx
16  q4  10  2010-12-02 12:34:27 1000    1000        pmx

I run four queries - one for each type, which select each p and order by time. This data is displayed on the front end of the website through four tables.

The queries that are slow are:

SELECT type,id,p,time,b,o
FROM zz
WHERE id = (SELECT MAX(id) FROM zz AS f
            WHERE f.p = zz.p
            AND type = 'pmx')
AND TYPE = 'pmx';

(then the same for three other types)

Does anyone have any tips for improving the actual query?

Thanks

Body:
How about something like

SELECT  zz.type,
        zz.id,
        zz.p,
        zz.time,
        zz.b,
        zz.o
FROM    zz INNER JOIN
        (
            SELECT  type,
                    MAX(id) MaxID
            FROM    zz
            WHERE   type IN ('1','2','3','4')
            GROUP BY type
        ) m ON  zz.type = m.type
            AND zz.ID = m.MaxID

Where ('1','2','3','4') are the four types in question.


问:
Ruby - elegantly convert variable to an array if not an array already
Given an array, a single element, or nil, obtain an array - the latter two being a single element array and an empty array respectively.

I mistakenly figured Ruby would work this way:

```<code>[1,2,3].to_a  #= [1,2,3]     # Already an array, so no change
1.to_a        #= [1]         # Creates an array and adds element
nil.to_a      #= []          # Creates empty array
</code>```

But what you really get is:

```<code>[1,2,3].to_a  #= [1,2,3]         # Hooray
1.to_a        #= NoMethodError   # Do not want
nil.to_a      #= []              # Hooray
</code>```

So to solve this, I either need to use another method, or I could meta program by modifying the to_a method of all classes I intend to use - which is not an option for me.

So a Method it is:

```<code>result = nums.class == "Array".constantize ? nums : (nums.class == "NilClass".constantize ? [] : ([]<<nums))
</code>```

The problem is that it is a bit of a mess. Is there an elegant way of doing this? (I would be amazed if this is the Ruby-ish way to solve this problem)

What applications does this have? Why even convert to an array?

In Rails' ActiveRecord, calling say, user.posts will either return an array of posts, a single post, or nil. When writing methods which work on the results of this, it is easiest to assume that the method will take an array, which may have zero, one, or many elements. Example method:

```<code>current_user.posts.inject(true) {|result, element| result and (element.some_boolean_condition)}
</code>```

答:
I've gone through all the answers and mostly don't work in ruby 2+

But elado has the most elegant solution i.e

With ActiveSupport (Rails): Array.wrap

Array.wrap([1, 2, 3])     # => [1, 2, 3]

Array.wrap(1)             # => [1]

Array.wrap(nil)           # => []

Array.wrap({a: 1, b: 2})  # => [{:a=>1, :b=>2}]

Sadly but this also doesn't work for ruby 2+ as you will get an error

```<code>undefined method `wrap' for Array:Class
</code>```

So in order to fix that you need to require.

require 'active_support/deprecation'

require 'active_support/core_ext/array/wrap'

Body:
Given an array, a single element, or nil, obtain an array - the latter two being a single element array and an empty array respectively.

I mistakenly figured Ruby would work this way:

[1,2,3].to_a  #= [1,2,3]     # Already an array, so no change
1.to_a        #= [1]         # Creates an array and adds element
nil.to_a      #= []          # Creates empty array

But what you really get is:

[1,2,3].to_a  #= [1,2,3]         # Hooray
1.to_a        #= NoMethodError   # Do not want
nil.to_a      #= []              # Hooray

So to solve this, I either need to use another method, or I could meta program by modifying the to_a method of all classes I intend to use - which is not an option for me.

So a Method it is:

result = nums.class == "Array".constantize ? nums : (nums.class == "NilClass".constantize ? [] : ([]<<nums))

The problem is that it is a bit of a mess. Is there an elegant way of doing this? (I would be amazed if this is the Ruby-ish way to solve this problem)

What applications does this have? Why even convert to an array?

In Rails' ActiveRecord, calling say, user.posts will either return an array of posts, a single post, or nil. When writing methods which work on the results of this, it is easiest to assume that the method will take an array, which may have zero, one, or many elements. Example method:

current_user.posts.inject(true) {|result, element| result and (element.some_boolean_condition)}

Body:
I've gone through all the answers and mostly don't work in ruby 2+

But elado has the most elegant solution i.e

With ActiveSupport (Rails): Array.wrap

Array.wrap([1, 2, 3])     # => [1, 2, 3]

Array.wrap(1)             # => [1]

Array.wrap(nil)           # => []

Array.wrap({a: 1, b: 2})  # => [{:a=>1, :b=>2}]

Sadly but this also doesn't work for ruby 2+ as you will get an error

undefined method `wrap' for Array:Class

So in order to fix that you need to require.

require 'active_support/deprecation'

require 'active_support/core_ext/array/wrap'


问:
How to add ' to generated link in php
```<code>$output .= '<a class="dropdown-toggle has-category" data-toggle="dropdown" href="'.$this->getLink($menu).'" target="'.$menu['target'].'">';
</code>```

I have php file with this code href="'.$this->getLink($menu).'"

its generates in html this href="https://www.myweb.com/"

Now i need to do it with onClick so that the output turned out like this

```<code>onclick="location.href='https://www.myweb.com'"
</code>```

Changed php code onclick="location.href='.$this->getLink($menu).'"

and result is onclick="location.href=https://www.myweb.com"
Link not working cuz lacks '
Can someone help me?

答:
Can you add this escaped single quote: \'?

echo '...onclick="location.href='.$this->getLink($menu).'\'"...';
```

(I added the echo to complete the code example).

Title: How to add ' to generated link in php

Body:
$output .= 'getLink($menu).'" target="'.$menu['target'].'">';

I have php file with this code href="'.$this->getLink($menu).'"

its generates in html this href="https://www.myweb.com/"

Now i need to do it with onClick so that the output turned out like this

onclick="location.href='https://www.myweb.com'"

Changed php code onclick="location.href='.$this->getLink($menu).'"

and result is onclick="location.href=https://www.myweb.com"
Link not working cuz lacks '
Can someone help me?

Body:
Can you add this escaped single quote: \'?

echo '...onclick="location.href='.$this->getLink($menu).'\'"...';

(I added the echo to complete the code example).


问:
How to make sure the the saved document fits the schema in MongoDB?
I have a MEAN app and I occasionally change the schema of the user document in MongoDB.

When I save a new document to the collection, I would like for the saved document to fit the schema exactly, otherwise raise an exception, is it possible?

Currently I can save partial document or even worse, try to save some non existing fields (in the schema) which MongoDB ignores.

Thanks

答:
Basically, Schema is the blueprint of a collection.  Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.

Now come to your issue

1: Can save partial document : If you do not want to save partial document you have to mark all fields as required in document.It will throw an error if you send partial document

2: try to save some non existing fields : As you already written mongoose schema ignores the non existing fields But if you want an error to be thrown if client send some unwanted data then you have to handle this on your route.For that i will recommend you to use a library called tv4

And also if u want to handle both points then also go for tv4


问:
transposing a matrix using pointer C
I am trying to write a code that transposes a matrix using pointer and memory allocation.

When I run it, it freezes from the part that produces a matrix with rand function in the program given below.

So I couldn't check whether two functions( transpose, printMatrix) work.

What am I doing wrong??

```<code># include <stdio.h>
# include <stdlib.h>

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    matrix[0] = malloc(rows*cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    printMatrix(**matrix, rows, cols);

    matrix = transpose(**matrix, rows, cols);

    printf("Transposed Matrix\n");
    printMatrix(**matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }
    return matrix;
}
void printMatrix(int **matrix, int m, int n){
    int i, j;

    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}
</code>```

答:
As the other answers stated your problem is in the allocation of memory for the matrix. But your problems don't stop there. You are also passing the value of the matrix when you want a double pointer in your functions.

Please refer to the corrected code:

```<code># include <stdio.h>
# include <stdlib.h>

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    for(int i=0;i<rows;i++)
      matrix[i] = malloc(cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    //Changed this, you where doing printMatrix(**matrix, rows, cols);
    printMatrix(matrix, rows, cols);

    //Changed this, you where doing matrix = transpose(**matrix, rows, cols);
    matrix = transpose(matrix, rows, cols);

    printf("Transposed Matrix\n");
    //Changed this, you where doing printMatrix(**matrix, rows, cols);
    printMatrix(matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }

}
void printMatrix(int **matrix, int m, int n){
    int i, j;
    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}
</code>```

Title: transposing a matrix using pointer C

Body:
I am trying to write a code that transposes a matrix using pointer and memory allocation.

When I run it, it freezes from the part that produces a matrix with rand function in the program given below.

So I couldn't check whether two functions( transpose, printMatrix) work.

What am I doing wrong??

# include <stdio.h>
# include <stdlib.h>

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    matrix[0] = malloc(rows*cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    printMatrix(**matrix, rows, cols);

    matrix = transpose(**matrix, rows, cols);

    printf("Transposed Matrix\n");
    printMatrix(**matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }
    return matrix;
}
void printMatrix(int **matrix, int m, int n){
    int i, j;

    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}

Body:
As the other answers stated your problem is in the allocation of memory for the matrix. But your problems don't stop there. You are also passing the value of the matrix when you want a double pointer in your functions.

Please refer to the corrected code:

# include <stdio.h>
# include <stdlib.h>

int** transpose (int **matrix, int m, int n);
void printMatrix(int **matrix, int m, int n);

int main (void){
    int rows, cols;
    int r, c;
    int **matrix;

    printf("Number of Rows : ");
    scanf("%d", &rows);
    printf("Number of Cols : ");
    scanf("%d", &cols);

    matrix = (int **)malloc(rows*sizeof(int*));
    for(int i=0;i<rows;i++)
      matrix[i] = malloc(cols*sizeof(int));

    srand(2016);

 //error starts from here
    for( r = 0; r < rows; r++ ){
        for( c = 0; c < cols; c++ ){
            *(*(matrix + r)+c) = rand() % 99 + 1;
        }
    }

    printf("Matrix produced with seed number 2016\n");
    //Changed this, you where doing printMatrix(**matrix, rows, cols);
    printMatrix(matrix, rows, cols);

    //Changed this, you where doing matrix = transpose(**matrix, rows, cols);
    matrix = transpose(matrix, rows, cols);

    printf("Transposed Matrix\n");
    //Changed this, you where doing printMatrix(**matrix, rows, cols);
    printMatrix(matrix, rows, cols);
}

int** transpose (int **matrix, int rows, int cols){
    int tmp, i ,j;

    if( rows < cols ){
        matrix[0] = (int *)realloc(matrix[0], rows*rows*sizeof(int));
    }
    else if(cols < rows){
        matrix = (int **)realloc(matrix, cols*sizeof(int*));
    }

    for (i = 0; i < rows; i++) {
        for (j = 0 ; j < cols; j++) {
            tmp = *(*(matrix + i) + j);
            *(*(matrix + i) + j) = *(*(matrix + j) + i);
            *(*(matrix + j) + i) = tmp;
        }
    }

}
void printMatrix(int **matrix, int m, int n){
    int i, j;
    for( i = 0; i < m; i++ ){
        for( j = 0; j < n; j++ ){
            printf("%3d", *(*(matrix + i )+j) );
        }
        printf("\n");
    }

}