问:
Occasional crash in Swift async/await concurrency code - only in release builds
I'm hitting an occasional crash in some code which uses Swift's new concurrency features. This crash never seems to happen on development builds, either in the simulator or when I install the code on a device directly from Xcode. However it's happening pretty frequently when folks install the code from TestFlight.

The actual crash is this:

```<code>Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000040
Exception Codes: 0x0000000000000001, 0x0000000000000040

Thread 6 name:
Thread 6 Crashed:
0   libswift_Concurrency.dylib          0x00000001e6df7440 swift::TaskGroup::offer(swift::AsyncTask*, swift::AsyncContext*) + 504 (TaskGroup.cpp:603)
1   libswift_Concurrency.dylib          0x00000001e6df3c5c swift::AsyncTask::completeFuture(swift::AsyncContext*) + 132 (Task.cpp:180)
2   libswift_Concurrency.dylib          0x00000001e6df54d0 completeTaskAndRelease(swift::AsyncContext*, swift::SwiftError*) + 128 (Task.cpp:323)
3   libswift_Concurrency.dylib          0x00000001e6df5425 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:365)
</code>```

I'm not sure exactly what line(s) of code this corresponds with, but it's likely somewhere in here:

```<code>class MyClass {

    var results: [String: Set<String>] = [:]

    func getSingleResult(index: Int) async -> (String, Set<String>) {
        // ....
    }

    func getAllResults(range: ClosedRange<Int>) async -> [String: Set<String>] {
        await withTaskGroup(
                of: (String, Set<String>).self,
                returning: [String: Set<String>].self
            ) { [self] group in
                for i in range {
                    group.addTask { await getSingleResult(index: i) }
                }

                var results: [String: Set<String>] = [:]

                for await result in group {
                    results[result.0] = result.1
                }

                return results
            }
    }

    func blockingDoWork(range: ClosedRange<Int>) {
        results = [:]

        let dispatchGroup = DispatchGroup()
        dispatchGroup.enter()

        Task.init {
            results = await getAllResults(range: range)
            dispatchGroup.leave()
        }

        dispatchGroup.wait()

        // Now do something with `results`
    }
</code>```

I'm trying to bridge the divide between synchronous and asynchronous code (perhaps the wrong way).  Basically I have a single thread/synchronous code which then creates a variable number of asynchronous calls and attempts to block until all those calls finish.  It aggregates the results of those calls in the results class member, which perhaps isn't the best approach but was the only way I could get the asynchronous code to communicate with the synchronous.

This code seems to run fine in a development build, and runs 1000s of times in a release build but then crashes.

I can't seem to turn on the thread sanitizer or address sanitizer because my Xcode project uses Swift Package Manager, and there's a bug when using those two which causes the build to fail.

Any ideas what might be going wrong?  I assume I'm getting lucky with the development builds and that I've got some fundamental problem in this code, but I don't know enough about the subtleties of Swift's new concurrency features to recognize it.

答:
You cannot use semaphores in conjunction with async-await. See Swift concurrency: Behind the scenes:

[Primitives] like semaphores ... are unsafe to use with Swift concurrency. This is because they hide dependency information from the Swift runtime, but introduce a dependency in execution in your code. Since the runtime is unaware of this dependency, it cannot make the right scheduling decisions and resolve them. In particular, do not use primitives that create unstructured tasks and then retroactively introduce a dependency across task boundaries by using a semaphore or an unsafe primitive. Such a code pattern means that a thread can block indefinitely against the semaphore until another thread is able to unblock it. This violates the runtime contract of forward progress for threads.

You might consider testing with the LIBDISPATCH_COOPERATIVE_POOL_STRICT environment variable as discussed here, in the same video.

You ask:

I'm trying to bridge the divide between synchronous and asynchronous code (perhaps the wrong way).

You should refactor the code that calls this synchronous method to adopt asynchronous pattern, and then excise all blocking API (e.g., semaphore wait, dispatch group wait, etc.). Those were anti-patterns in the GCD world and are to be avoided within Swift concurrency. I understand why developers who are unfamiliar with asynchronous programming are so attracted to those synchronous anti-patterns, but it has always been a mistake, and should be excised from one’s code.

Bottom line, in Swift concurrency one must “maintain a runtime contract that threads are always able to make forward progress.” Just embrace asynchronous patterns (i.e., stay within async-await without any old-school thread-blocking techniques) and you should be good.

FWIW, the Swift concurrency: Update a sample app shows interesting techniques for incrementally updating an old app. E.g., mark this blocking method as deprecated, and then the compiler will warn you where it is called and you can direct your refactoring efforts to those offending routines.

Body:
I'm hitting an occasional crash in some code which uses Swift's new concurrency features. This crash never seems to happen on development builds, either in the simulator or when I install the code on a device directly from Xcode. However it's happening pretty frequently when folks install the code from TestFlight.

The actual crash is this:

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000040
Exception Codes: 0x0000000000000001, 0x0000000000000040

Thread 6 name:
Thread 6 Crashed:
0   libswift_Concurrency.dylib          0x00000001e6df7440 swift::TaskGroup::offer(swift::AsyncTask*, swift::AsyncContext*) + 504 (TaskGroup.cpp:603)
1   libswift_Concurrency.dylib          0x00000001e6df3c5c swift::AsyncTask::completeFuture(swift::AsyncContext*) + 132 (Task.cpp:180)
2   libswift_Concurrency.dylib          0x00000001e6df54d0 completeTaskAndRelease(swift::AsyncContext*, swift::SwiftError*) + 128 (Task.cpp:323)
3   libswift_Concurrency.dylib          0x00000001e6df5425 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:365)

I'm not sure exactly what line(s) of code this corresponds with, but it's likely somewhere in here:

class MyClass {

    var results: [String: Set<String>] = [:]

    func getSingleResult(index: Int) async -> (String, Set<String>) {
        // ....
    }

    func getAllResults(range: ClosedRange<Int>) async -> [String: Set<String>] {
        await withTaskGroup(
                of: (String, Set<String>).self,
                returning: [String: Set<String>].self
            ) { [self] group in
                for i in range {
                    group.addTask { await getSingleResult(index: i) }
                }

                var results: [String: Set<String>] = [:]

                for await result in group {
                    results[result.0] = result.1
                }

                return results
            }
    }

    func blockingDoWork(range: ClosedRange<Int>) {
        results = [:]

        let dispatchGroup = DispatchGroup()
        dispatchGroup.enter()

        Task.init {
            results = await getAllResults(range: range)
            dispatchGroup.leave()
        }

        dispatchGroup.wait()

        // Now do something with `results`
    }

I'm trying to bridge the divide between synchronous and asynchronous code (perhaps the wrong way).  Basically I have a single thread/synchronous code which then creates a variable number of asynchronous calls and attempts to block until all those calls finish.  It aggregates the results of those calls in the results class member, which perhaps isn't the best approach but was the only way I could get the asynchronous code to communicate with the synchronous.

This code seems to run fine in a development build, and runs 1000s of times in a release build but then crashes.

I can't seem to turn on the thread sanitizer or address sanitizer because my Xcode project uses Swift Package Manager, and there's a bug when using those two which causes the build to fail.

Any ideas what might be going wrong?  I assume I'm getting lucky with the development builds and that I've got some fundamental problem in this code, but I don't know enough about the subtleties of Swift's new concurrency features to recognize it.


来源: stackexchange

问:
TypeError: Object(...) is not a function in Vue
I am new to Vue and trying to handle form. I am making a web app to manage meetings and for this I have multi-step form which will handle visitor and host data. When I click submit button, I get following error:-
TypeError: Object(...) is not a function
. I searched for it on stackoverflow but couldn't get much clue.
Following is my code:-

scheduleMeeting.js

```<code><template>
    <el-container>
        <el-row>

            <el-col class="desc" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                <img src="../assets/meeting.svg" alt="meeting-image" class="image"/>
                <div>
                    <h1 class="image-caption">Schedule Meetings With Ease!</h1>
                    <p class="image-sub-caption">Managing Meetings Now Much Easier</p>
                    <ul class="feature-list">
                        <li>Get instant meeting confirmation on email and mobile!</li>
                        <li>Schedule meeting from anywhere, anytime!</li>
                        <li>Schedule meeting using your mobile</li>
                        <li>Get check out email on your mailing address</li>
                        <li>Keep Track of All Visitors and Hosts</li>
                    </ul>
                </div>
            </el-col>

            <el-col class="form-div" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                <el-col class="steps">
                    <el-steps align-center class="steps" :active="active">
                        <el-step title="Step 1" description="Visitor Details"></el-step>
                        <el-step title="Step 2" description="Host Details"></el-step>
                    </el-steps>
                </el-col>

                <el-form ref="form" :model="form" label-width="120px">
                    <div :class="{'show':isVisitor, 'hide':!isVisitor}">
                        <el-input
                                name="visitorName"
                                v-validate="'required|alpha_spaces'"
                                prefix-icon="el-icon-user"
                                class="form-input"
                                placeholder="Visitor Name"
                                v-model="form.visitor.name"/>
                        <p v-if="errors.has('visitorName')" class="registration-error-message">
                            {{errors.first("visitorName")}}</p>

                        <el-input
                                name="visitorEmail"
                                v-validate="'required|email'"
                                prefix-icon="el-icon-message"
                                class="form-input"
                                placeholder="Visitor Email"
                                v-model="form.visitor.email"/>
                        <p v-if="errors.has('visitorEmail')" class="registration-error-message">
                            {{errors.first("visitorEmail")}}</p>
                        <vue-phone-number-input
                                v-validate="'required'"
                                name="visitorPhoneNo"
                                v-model="form.visitor.phone_no"
                                class="form-input"/>
                        <p v-if="errors.has('visitorPhoneNo')" class="registration-error-message">
                            {{errors.first("visitorPhoneNo")}}</p>
                        {{this.form.visitor.phone_no}}
                        <el-row>
                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                <el-date-picker
                                        v-validate="'required'"
                                        name="visitorCheckIn"
                                        class="form-input"
                                        v-model="form.visitor.check_in"
                                        type="datetime"
                                        ref="check_in"
                                        placeholder="Visitor Check In"/>
                                <p v-if="errors.has('visitorCheckIn')" class="registration-error-message">
                                    {{errors.first("visitorCheckIn")}}</p>
                            </el-col>
                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                <el-date-picker
                                        v-validate="'required|after:check_in'"
                                        name="visitorCheckOut"
                                        class="form-input"
                                        v-model="form.visitor.check_out"
                                        type="datetime"
                                        placeholder="Visitor Check Out"/>
                                <p v-if="errors.has('visitorCheckOut')" class="registration-error-message">
                                    {{errors.first("visitorCheckOut")}}</p>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-button
                                    @click="goToStepTwo"
                                    class="button"
                                    type="primary"
                                    round>Next <i class="el-icon-arrow-right"></i>
                            </el-button>
                        </el-row>
                    </div>
                    <div :class="{'show':!isVisitor, 'hide':isVisitor}">
                        <el-input
                                name="hostName"
                                v-validate="'required|alpha_spaces'"
                                prefix-icon="el-icon-user"
                                class="form-input"
                                placeholder="Host Name"
                                v-model="form.name"/>
                        <p v-if="errors.has('hostName')" class="registration-error-message">
                            {{errors.first("hostName")}}</p>
                        <el-input
                                name="hostEmail"
                                v-validate="'required|email'"
                                prefix-icon="el-icon-message"
                                class="form-input"
                                placeholder="Host Email"
                                v-model="form.email"/>
                        <p v-if="errors.has('hostEmail')" class="registration-error-message">
                            {{errors.first("hostEmail")}}</p>
                        <vue-phone-number-input
                                name="hostPhoneNo"
                                v-validate="'required'"
                                v-model="form.phone_no"
                                class="form-input"/>
                        <p v-if="errors.has('hostPhoneNo')" class="registration-error-message">
                            {{errors.first("hostPhoneNo")}}</p>
                        <el-button
                                icon="el-icon-arrow-left"
                                plain
                                @click="goToStepOne"
                                class="button"
                                round>Back
                        </el-button>
                        <el-button
                                @click="createMeeting"
                                class="button"
                                type="primary"
                                round>Submit
                        </el-button>
                    </div>
                </el-form>

                <div v-if="isMeetingConfirmed">

                </div>
            </el-col>
        </el-row>
    </el-container>
</template>

<script>
    import scheduleMeeting from "../api/meeting"

    export default {
        data: () => ({
            active: 1,
            isVisitor: true,
            isMeetingConfirmed: false,
            form: {
                name: '',
                email: '',
                phone_no: '',
                visitor: {
                    name: '',
                    email: '',
                    phone_no: '',
                    check_in: '',
                    check_out: ''
                }
            }
        }),
        methods: {
            goToStepOne() {
                this.isVisitor = true
                this.active = 1
            },
            async goToStepTwo() {
                if (
                    await this.$validator.validate('visitorName', this.form.visitor.name) &&
                    await this.$validator.validate('visitorEmail', this.form.visitor.email) &&
                    await this.$validator.validate('visitorPhoneNo', this.form.visitor.phone_no) &&
                    await this.$validator.validate('visitorCheckIn', this.form.visitor.check_in) &&
                    await this.$validator.validate('visitorCheckOut', this.form.visitor.check_out)) {
                    this.isVisitor = false
                    this.active = 2
                }
            },
            async createMeeting() {
                var global = this;
                this.$validator.validate().then(valid => {
                    if (valid) {
                        scheduleMeeting(global.form)
                            .then(() => this.isMeetingConfirmed = true)
                            .catch(error => {
                                this.$message({
                                    showClose: true,
                                    type: 'error',
                                    message: error.response.data
                                })
                            })
                    }
                });

            }
        }
    };
</script>

<style lang="css">
    .show {
        display: block;
    }

    .hide {
        display: none;
    }

    .image {
        width: 80%;
        margin: 1rem auto;
    }

    .steps {
        margin: 0 0 1rem 0;
    }

    .image-sub-caption {
        color: rgb(120, 120, 120);
        font-weight: 600;
        padding-bottom: 1rem;
    }

    .feature-list {
        margin: 1rem;
        list-style: none;
    }

    .feature-list > li {
        font-weight: 400;
        color: rgb(120, 120, 120);
        padding: 0.4rem 0;
    }

    .desc {
        background-color: #e6f1ff;
        text-align: center;
    }

    .registration-error-message {
        color: #f56c6c;
        font-size: 13px;
        line-height: 1;
        padding-top: 4px;
        position: relative;
        margin: -1rem 0 1rem 0;
        top: 100%;
        left: 0;
    }

    .form-div {
        padding: 3rem;
    }

    .form-input {
        border: none !important;
        margin: 1rem 0;
    }

    .button {
        margin: 2rem 0;
    }
</style>

</code>```

meeting.js

```<code>import session from "./session";

export default {
    scheduleMeeting(meeting) {
        return session.post("/meeting/create/", {
            ...meeting
        })
    }
};
</code>```

Complete error message log is as follows:-

```<code>Uncaught (in promise) TypeError: Object(...) is not a function
    at eval (ScheduleMeeting.vue?34e8:184)
eval    @   ScheduleMeeting.vue?34e8:184
Promise.then (async)
createMeeting$  @   ScheduleMeeting.vue?34e8:182
tryCatch    @   vue-phone-number-inp…common.js?7bec:2629
invoke  @   vue-phone-number-inp…common.js?7bec:2855
prototype.<computed>    @   vue-phone-number-inp…common.js?7bec:2681
tryCatch    @   vue-phone-number-inp…common.js?7bec:2629
invoke  @   vue-phone-number-inp…common.js?7bec:2719
eval    @   vue-phone-number-inp…common.js?7bec:2754
callInvokeWithMethodAndArg  @   vue-phone-number-inp…common.js?7bec:2753
enqueue @   vue-phone-number-inp…common.js?7bec:2776
prototype.<computed>    @   vue-phone-number-inp…common.js?7bec:2681
module.exports.96cf.exports.async   @   vue-phone-number-inp…common.js?7bec:2800
createMeeting   @   ScheduleMeeting.vue?34e8:163
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
invoker @   vue.runtime.esm.js?2b0e:2179
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
Vue.$emit   @   vue.runtime.esm.js?2b0e:3882
handleClick @   element-ui.common.js?5c96:9393
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
invoker @   vue.runtime.esm.js?2b0e:2179
original._wrapper   @   vue.runtime.esm.js?2b0e:6911
</code>```

Any hint would be of great help!

答: I had this problem recently too，I changed the version of vue-router "version": "3.5.2",Works fine</p>

ContentLicense: CC BY-SA 4.0

Body:
I am new to Vue and trying to handle form. I am making a web app to manage meetings and for this I have multi-step form which will handle visitor and host data. When I click submit button, I get following error:-
TypeError: Object(...) is not a function
. I searched for it on stackoverflow but couldn't get much clue.
Following is my code:-

scheduleMeeting.js

<template>
    <el-container>
        <el-row>

            <el-col class="desc" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">

Schedule Meetings With Ease!

Managing Meetings Now Much Easier

Get instant meeting confirmation on email and mobile!

Schedule meeting from anywhere, anytime!

Schedule meeting using your mobile

Get check out email on your mailing address

Keep Track of All Visitors and Hosts

            </el-col>

            <el-col class="form-div" :xs="24" :sm="24" :md="24" :lg="12" :xl="12">
                <el-col class="steps">
                    <el-steps align-center class="steps" :active="active">
                        <el-step title="Step 1" description="Visitor Details"></el-step>
                        <el-step title="Step 2" description="Host Details"></el-step>
                    </el-steps>
                </el-col>

                <el-form ref="form" :model="form" label-width="120px">

                        <el-input
                                name="visitorName"
                                v-validate="'required|alpha_spaces'"
                                prefix-icon="el-icon-user"
                                class="form-input"
                                placeholder="Visitor Name"
                                v-model="form.visitor.name"/>

                            {{errors.first("visitorName")}}

                        <el-input
                                name="visitorEmail"
                                v-validate="'required|email'"
                                prefix-icon="el-icon-message"
                                class="form-input"
                                placeholder="Visitor Email"
                                v-model="form.visitor.email"/>

                            {{errors.first("visitorEmail")}}

                        <vue-phone-number-input
                                v-validate="'required'"
                                name="visitorPhoneNo"
                                v-model="form.visitor.phone_no"
                                class="form-input"/>

                            {{errors.first("visitorPhoneNo")}}

                        {{this.form.visitor.phone_no}}
                        <el-row>
                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                <el-date-picker
                                        v-validate="'required'"
                                        name="visitorCheckIn"
                                        class="form-input"
                                        v-model="form.visitor.check_in"
                                        type="datetime"
                                        ref="check_in"
                                        placeholder="Visitor Check In"/>

                                    {{errors.first("visitorCheckIn")}}

                            </el-col>
                            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                                <el-date-picker
                                        v-validate="'required|after:check_in'"
                                        name="visitorCheckOut"
                                        class="form-input"
                                        v-model="form.visitor.check_out"
                                        type="datetime"
                                        placeholder="Visitor Check Out"/>

                                    {{errors.first("visitorCheckOut")}}

                            </el-col>
                        </el-row>
                        <el-row>
                            <el-button
                                    @click="goToStepTwo"
                                    class="button"
                                    type="primary"
                                    round>Next
                            </el-button>
                        </el-row>

                        <el-input
                                name="hostName"
                                v-validate="'required|alpha_spaces'"
                                prefix-icon="el-icon-user"
                                class="form-input"
                                placeholder="Host Name"
                                v-model="form.name"/>

                            {{errors.first("hostName")}}

                        <el-input
                                name="hostEmail"
                                v-validate="'required|email'"
                                prefix-icon="el-icon-message"
                                class="form-input"
                                placeholder="Host Email"
                                v-model="form.email"/>

                            {{errors.first("hostEmail")}}

                        <vue-phone-number-input
                                name="hostPhoneNo"
                                v-validate="'required'"
                                v-model="form.phone_no"
                                class="form-input"/>

                            {{errors.first("hostPhoneNo")}}

                        <el-button
                                icon="el-icon-arrow-left"
                                plain
                                @click="goToStepOne"
                                class="button"
                                round>Back
                        </el-button>
                        <el-button
                                @click="createMeeting"
                                class="button"
                                type="primary"
                                round>Submit
                        </el-button>

                </el-form>

            </el-col>
        </el-row>
    </el-container>
</template>

meeting.js

import session from "./session";

export default {
    scheduleMeeting(meeting) {
        return session.post("/meeting/create/", {
            ...meeting
        })
    }
};

Complete error message log is as follows:-

Uncaught (in promise) TypeError: Object(...) is not a function
    at eval (ScheduleMeeting.vue?34e8:184)
eval    @   ScheduleMeeting.vue?34e8:184
Promise.then (async)
createMeeting$  @   ScheduleMeeting.vue?34e8:182
tryCatch    @   vue-phone-number-inp…common.js?7bec:2629
invoke  @   vue-phone-number-inp…common.js?7bec:2855
prototype.<computed>    @   vue-phone-number-inp…common.js?7bec:2681
tryCatch    @   vue-phone-number-inp…common.js?7bec:2629
invoke  @   vue-phone-number-inp…common.js?7bec:2719
eval    @   vue-phone-number-inp…common.js?7bec:2754
callInvokeWithMethodAndArg  @   vue-phone-number-inp…common.js?7bec:2753
enqueue @   vue-phone-number-inp…common.js?7bec:2776
prototype.<computed>    @   vue-phone-number-inp…common.js?7bec:2681
module.exports.96cf.exports.async   @   vue-phone-number-inp…common.js?7bec:2800
createMeeting   @   ScheduleMeeting.vue?34e8:163
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
invoker @   vue.runtime.esm.js?2b0e:2179
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
Vue.$emit   @   vue.runtime.esm.js?2b0e:3882
handleClick @   element-ui.common.js?5c96:9393
invokeWithErrorHandling @   vue.runtime.esm.js?2b0e:1854
invoker @   vue.runtime.esm.js?2b0e:2179
original._wrapper   @   vue.runtime.esm.js?2b0e:6911

Any hint would be of great help!


问:
changing multiple column values given a condition in dplyr
I'm looking to find a simple way to do something like the following but with dplyr, essentially just replacing the values in 3 columns with NA when the condition is met.

```<code>dta[dta$na.ind == 1, c('x1', 'x2', 'x3')] <- NA
</code>```

The only method I can think of using dplyr is the following, but I feel there should be a simpler way

```<code>dta <- dta %>%
    mutate(x1 = ifelse(na.ind == 1, NA, x1),
           x2 = ifelse(na.ind == 1, NA, x2),
           x3 = ifelse(na.ind == 1, NA, x3))
</code>```

Thanks!

答:
Since scoped verbs like mutate_at, mutate_all etc. are being replaced by across, you could now make the following adjustments to Psidom's answer:

```<code>> dta <- data.frame(na.ind = 1:3, x1 = 2:4, x2 = 2:4, x3 = 2:4, x4 = 2:4)
> dta
  na.ind x1 x2 x3 x4
1      1  2  2  2  2
2      2  3  3  3  3
3      3  4  4  4  4

> dta %>% mutate(across(c(x1, x2, x3), ~ ifelse(na.ind == 1, NA, .)))
  na.ind x1 x2 x3 x4
1      1 NA NA NA  2
2      2  3  3  3  3
3      3  4  4  4  4
</code>```

See https://dplyr.tidyverse.org/reference/across.html for more information on across.

ContentLicense: CC BY-SA 3.0

Body:
I'm looking to find a simple way to do something like the following but with dplyr, essentially just replacing the values in 3 columns with NA when the condition is met.

dta[dta$na.ind == 1, c('x1', 'x2', 'x3')] <- NA

The only method I can think of using dplyr is the following, but I feel there should be a simpler way

dta <- dta %>%
    mutate(x1 = ifelse(na.ind == 1, NA, x1),
           x2 = ifelse(na.ind == 1, NA, x2),
           x3 = ifelse(na.ind == 1, NA, x3))

Thanks!

Body:
Since scoped verbs like mutate_at, mutate_all etc. are being replaced by across, you could now make the following adjustments to Psidom's answer:

> dta <- data.frame(na.ind = 1:3, x1 = 2:4, x2 = 2:4, x3 = 2:4, x4 = 2:4)
> dta
  na.ind x1 x2 x3 x4
1      1  2  2  2  2
2      2  3  3  3  3
3      3  4  4  4  4

> dta %>% mutate(across(c(x1, x2, x3), ~ ifelse(na.ind == 1, NA, .)))
  na.ind x1 x2 x3 x4
1      1 NA NA NA  2
2      2  3  3  3  3
3      3  4  4  4  4

See https://dplyr.tidyverse.org/reference/across.html for more information on across.


问:
How can I convert a decimal to a fraction?
How do I convert a indefinite decimal (i.e. .333333333...)  to a string fraction representation (i.e. "1/3"). I am using VBA and the following is the code I used (i get an overflow error at the line "b = a Mod b":</p>

```<code>Function GetFraction(ByVal Num As Double) As String

    If Num = 0# Then
        GetFraction = "None"
    Else
        Dim WholeNumber As Integer
        Dim DecimalNumber As Double
        Dim Numerator As Double
        Dim Denomenator As Double
        Dim a, b, t As Double

        WholeNumber = Fix(Num)
        DecimalNumber = Num - Fix(Num)
        Numerator = DecimalNumber * 10 ^ (Len(CStr(DecimalNumber)) - 2)
        Denomenator = 10 ^ (Len(CStr(DecimalNumber)) - 2)
        If Numerator = 0 Then
            GetFraction = WholeNumber
        Else
            a = Numerator
            b = Denomenator
            t = 0

            While b <> 0
                t = b
                b = a Mod b
                a = t
            Wend
            If WholeNumber = 0 Then
                GetFraction = CStr(Numerator / a) & "/" & CStr(Denomenator / a)
            Else
                GetFraction = CStr(WholeNumber) & " " & CStr(Numerator / a) & "/" & CStr(Denomenator / a)
            End If
        End If
    End If
End Function
</code>```

答:
Python has a nice routine in its fractions module. Here is the working portion that converts a n/d into the closest approximation N/D where D <= some maximum value. e.g. if you want to find the closest fraction to 0.347, let n=347,d=1000 and max_denominator be 100 and you will obtain (17, 49) which is as close as you can get for denominators less than or equal to 100. The '//' operator is integer division so that 2//3 gives 0, i.e. a//b = int(a/b).</p>

```<code>def approxFrac(n,d,max_denominator):

    #give a representation of n/d as N/D where D<=max_denominator
    #from python 2.6 fractions.py
    #
    # reduce by gcd and only run algorithm if d>maxdenominator
    g, b = n, d
    while b:
        g, b = b, g%b
    n, d = n/g, d/g
    if d <= max_denominator:
        return (n,d)
    nn, dd = n, d
    p0, q0, p1, q1 = 0, 1, 1, 0
    while True:
        a = nn//dd
        q2 = q0+a*q1
        if q2 > max_denominator:
            break
        p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
        nn, dd = dd, nn-a*dd

    k = (max_denominator-q0)//q1
    bound1 = (p0+k*p1, q0+k*q1)
    bound2 = (p1, q1)
    if abs(bound2[0]*d - bound2[1]*n) <= abs(bound1[0]*d - bound1[1]*n):
        return bound2
    else:
        return bound1
</code>```

OwnerDisplayName: CornyD

LastEditorDisplayName: Brann

ContentLicense: CC BY-SA 2.5

Body:
How do I convert a indefinite decimal (i.e. .333333333...)  to a string fraction representation (i.e. "1/3"). I am using VBA and the following is the code I used (i get an overflow error at the line "b = a Mod b":

Function GetFraction(ByVal Num As Double) As String

    If Num = 0# Then
        GetFraction = "None"
    Else
        Dim WholeNumber As Integer
        Dim DecimalNumber As Double
        Dim Numerator As Double
        Dim Denomenator As Double
        Dim a, b, t As Double

        WholeNumber = Fix(Num)
        DecimalNumber = Num - Fix(Num)
        Numerator = DecimalNumber * 10 ^ (Len(CStr(DecimalNumber)) - 2)
        Denomenator = 10 ^ (Len(CStr(DecimalNumber)) - 2)
        If Numerator = 0 Then
            GetFraction = WholeNumber
        Else
            a = Numerator
            b = Denomenator
            t = 0

            While b <> 0
                t = b
                b = a Mod b
                a = t
            Wend
            If WholeNumber = 0 Then
                GetFraction = CStr(Numerator / a) & "/" & CStr(Denomenator / a)
            Else
                GetFraction = CStr(WholeNumber) & " " & CStr(Numerator / a) & "/" & CStr(Denomenator / a)
            End If
        End If
    End If
End Function

Body:
Python has a nice routine in its fractions module. Here is the working portion that converts a n/d into the closest approximation N/D where D <= some maximum value. e.g. if you want to find the closest fraction to 0.347, let n=347,d=1000 and max_denominator be 100 and you will obtain (17, 49) which is as close as you can get for denominators less than or equal to 100. The '//' operator is integer division so that 2//3 gives 0, i.e. a//b = int(a/b).

def approxFrac(n,d,max_denominator):

    #give a representation of n/d as N/D where D<=max_denominator
    #from python 2.6 fractions.py
    #
    # reduce by gcd and only run algorithm if d>maxdenominator
    g, b = n, d
    while b:
        g, b = b, g%b
    n, d = n/g, d/g
    if d <= max_denominator:
        return (n,d)
    nn, dd = n, d
    p0, q0, p1, q1 = 0, 1, 1, 0
    while True:
        a = nn//dd
        q2 = q0+a*q1
        if q2 > max_denominator:
            break
        p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
        nn, dd = dd, nn-a*dd

    k = (max_denominator-q0)//q1
    bound1 = (p0+k*p1, q0+k*q1)
    bound2 = (p1, q1)
    if abs(bound2[0]*d - bound2[1]*n) <= abs(bound1[0]*d - bound1[1]*n):
        return bound2
    else:
        return bound1


问:
how to record screen video as like Talking Tomcat application does in iphone?
hey i m trying the record the gameplay of my game so that i can upload its video to youtube from device itself...m trying to do same thing as Talking tomcat app for iphone..recording the video then playing it ,etc...

i m using glReadPixels() for reading framebuffer data and then writing it to video with the help of AVAssetWriter in AVFoundation framwork. But reading the data on each drawing decreases the FPS from around 30-35 to 2-3 only while using glReadPixels.

i think Talking tomcat is also made with the help of Opengl ES it also has the video recording facility but it doesnot slows down while reading each frame any idea.... ?

答:
In case someone want to implement the same..i figured out myself.
First of all to my surprise i found that talking tomcat is not a 3D game app...it uses frame animations for all movements. and if some one wants to capture the that kind of view then they can use following code---

```<code>UIGraphicsBeginImageContext(self.view.bounds.size); //self.view.window.frame.size
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);
</code>```

and then use AVAssetWriter for creating the video from that frames. ofcourse you can find code for that in some other post..  For me its not useful as i have to capture 3D part..
Cheers

Body:
In case someone want to implement the same..i figured out myself.
First of all to my surprise i found that talking tomcat is not a 3D game app...it uses frame animations for all movements. and if some one wants to capture the that kind of view then they can use following code---

UIGraphicsBeginImageContext(self.view.bounds.size); //self.view.window.frame.size
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIImageWriteToSavedPhotosAlbum(viewImage, nil, nil, nil);

and then use AVAssetWriter for creating the video from that frames. ofcourse you can find code for that in some other post..  For me its not useful as i have to capture 3D part..
Cheers


问:
Errors trying to install PostgreSQL on Debian 11
Fail to install PostgreSQL on Debian 11

First time to install package: sudo apt install postgresql

```<code>...
Unpacking postgresql (13+225) ...
Setting up postgresql-client-common (225) ...
Setting up libpq5:amd64 (13.5-0+deb11u1) ...
Setting up postgresql-client-13 (13.5-0+deb11u1) ...
double free or corruption (!prev)
dpkg: error processing package postgresql-client-13 (--configure):
 installed postgresql-client-13 package post-installation script subprocess was killed by signal (Aborted)
Setting up libz3-4:amd64 (4.8.10-1) ...
Setting up libllvm11:amd64 (1:11.0.1-2) ...
Setting up postgresql-common (225) ...
Adding user postgres to group ssl-cert

Creating config file /etc/postgresql-common/createcluster.conf with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
Removing obsolete dictionary files:
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /lib/systemd/system/postgresql.service.
dpkg: dependency problems prevent configuration of postgresql-13:
 postgresql-13 depends on postgresql-client-13; however:
  Package postgresql-client-13 is not configured yet.

dpkg: error processing package postgresql-13 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of postgresql:
 postgresql depends on postgresql-13; however:
  Package postgresql-13 is not configured yet.

dpkg: error processing package postgresql (--configure):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.9.4-2) ...
Processing triggers for libc-bin (2.31-13+deb11u2) ...
Errors were encountered while processing:
 postgresql-client-13
 postgresql-13
 postgresql
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

Look that package postgresql-client-13 appears with "iF" state (configuration failed) and other failed packages with "iU" state

dpkg -l | grep postgres

```<code>iU  postgresql                    13+225                         all          object-relational SQL database (supported version)
iU  postgresql-13                 13.5-0+deb11u1                 amd64        The World's Most Advanced Open Source Relational Database
iF  postgresql-client-13          13.5-0+deb11u1                 amd64        front-end programs for PostgreSQL 13
ii  postgresql-client-common      225                            all          manager for multiple PostgreSQL client versions
ii  postgresql-common             225                            all          PostgreSQL database-cluster manager
</code>```

Second letter -> current package state:

```<code>i ... installed
U ... unpacked
F ... half-configured (configuration failed for some reason)
</code>```

Get packages states table at:
https://askubuntu.com/questions/18804/what-do-the-various-dpkg-flags-like-ii-rc-mean

I removed all PostgreSQL packages and all files with: sudo apt purge postgresql

After that I tried again to install postgresql-client-13, which returned the error above. sudo apt install postgresql-client-13

```<code>Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libllvm11 libz3-4
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  postgresql-client-common
Suggested packages:
  postgresql-13 postgresql-doc-13
The following NEW packages will be installed:
  postgresql-client-13 postgresql-client-common
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/1,603 kB of archives.
After this operation, 6,789 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Selecting previously unselected package postgresql-client-common.
(Reading database ... 39655 files and directories currently installed.)
Preparing to unpack .../postgresql-client-common_225_all.deb ...
Unpacking postgresql-client-common (225) ...
Selecting previously unselected package postgresql-client-13.
Preparing to unpack .../postgresql-client-13_13.5-0+deb11u1_amd64.deb ...
Unpacking postgresql-client-13 (13.5-0+deb11u1) ...
Setting up postgresql-client-common (225) ...
Setting up postgresql-client-13 (13.5-0+deb11u1) ...
double free or corruption (!prev)
dpkg: error processing package postgresql-client-13 (--configure):
 installed postgresql-client-13 package post-installation script subprocess was killed by signal (Aborted)
Processing triggers for man-db (2.9.4-2) ...
Errors were encountered while processing:
 postgresql-client-13
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)
</code>```

答:
The problem is related to the existence of the previously installed snoopy package.

Uninstall snoopy with sudo apt remove snoopy and, after that install PostgreSQL or postgresql-client-13.

Body:
Fail to install PostgreSQL on Debian 11

First time to install package: sudo apt install postgresql

...
Unpacking postgresql (13+225) ...
Setting up postgresql-client-common (225) ...
Setting up libpq5:amd64 (13.5-0+deb11u1) ...
Setting up postgresql-client-13 (13.5-0+deb11u1) ...
double free or corruption (!prev)
dpkg: error processing package postgresql-client-13 (--configure):
 installed postgresql-client-13 package post-installation script subprocess was killed by signal (Aborted)
Setting up libz3-4:amd64 (4.8.10-1) ...
Setting up libllvm11:amd64 (1:11.0.1-2) ...
Setting up postgresql-common (225) ...
Adding user postgres to group ssl-cert

Creating config file /etc/postgresql-common/createcluster.conf with new version
Building PostgreSQL dictionaries from installed myspell/hunspell packages...
Removing obsolete dictionary files:
Created symlink /etc/systemd/system/multi-user.target.wants/postgresql.service → /lib/systemd/system/postgresql.service.
dpkg: dependency problems prevent configuration of postgresql-13:
 postgresql-13 depends on postgresql-client-13; however:
  Package postgresql-client-13 is not configured yet.

dpkg: error processing package postgresql-13 (--configure):
 dependency problems - leaving unconfigured
dpkg: dependency problems prevent configuration of postgresql:
 postgresql depends on postgresql-13; however:
  Package postgresql-13 is not configured yet.

dpkg: error processing package postgresql (--configure):
 dependency problems - leaving unconfigured
Processing triggers for man-db (2.9.4-2) ...
Processing triggers for libc-bin (2.31-13+deb11u2) ...
Errors were encountered while processing:
 postgresql-client-13
 postgresql-13
 postgresql
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)

Look that package postgresql-client-13 appears with "iF" state (configuration failed) and other failed packages with "iU" state

dpkg -l | grep postgres

iU  postgresql                    13+225                         all          object-relational SQL database (supported version)
iU  postgresql-13                 13.5-0+deb11u1                 amd64        The World's Most Advanced Open Source Relational Database
iF  postgresql-client-13          13.5-0+deb11u1                 amd64        front-end programs for PostgreSQL 13
ii  postgresql-client-common      225                            all          manager for multiple PostgreSQL client versions
ii  postgresql-common             225                            all          PostgreSQL database-cluster manager

Second letter -> current package state:

i ... installed
U ... unpacked
F ... half-configured (configuration failed for some reason)

Get packages states table at:
https://askubuntu.com/questions/18804/what-do-the-various-dpkg-flags-like-ii-rc-mean

I removed all PostgreSQL packages and all files with: sudo apt purge postgresql

After that I tried again to install postgresql-client-13, which returned the error above. sudo apt install postgresql-client-13

Reading package lists... Done
Building dependency tree... Done
Reading state information... Done
The following packages were automatically installed and are no longer required:
  libllvm11 libz3-4
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
  postgresql-client-common
Suggested packages:
  postgresql-13 postgresql-doc-13
The following NEW packages will be installed:
  postgresql-client-13 postgresql-client-common
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 0 B/1,603 kB of archives.
After this operation, 6,789 kB of additional disk space will be used.
Do you want to continue? [Y/n] y
Selecting previously unselected package postgresql-client-common.
(Reading database ... 39655 files and directories currently installed.)
Preparing to unpack .../postgresql-client-common_225_all.deb ...
Unpacking postgresql-client-common (225) ...
Selecting previously unselected package postgresql-client-13.
Preparing to unpack .../postgresql-client-13_13.5-0+deb11u1_amd64.deb ...
Unpacking postgresql-client-13 (13.5-0+deb11u1) ...
Setting up postgresql-client-common (225) ...
Setting up postgresql-client-13 (13.5-0+deb11u1) ...
double free or corruption (!prev)
dpkg: error processing package postgresql-client-13 (--configure):
 installed postgresql-client-13 package post-installation script subprocess was killed by signal (Aborted)
Processing triggers for man-db (2.9.4-2) ...
Errors were encountered while processing:
 postgresql-client-13
needrestart is being skipped since dpkg has failed
E: Sub-process /usr/bin/dpkg returned an error code (1)


问:
How to instantiate an Agent via code in Anylogic
I'm having an issue with Anylogic: I'm writing a function where I need to declare a new item of the type of an already existing Agent type.
If I declare it with the code:

MyAgent name = new MyAgent();

everything is ok but when I try to execute a function to change the value of an internal value,

name.func();

it gives me a NullPointerException, because the internal variable of the declared MyAgent seems not to exist.
What am I missing?
Thanks a lot in advance for your help

答:
Certain functions are not available inside agents that get created programmatically, like the default random number generator and certain other utility functions that get passed to agents.

So if you do this for example it wont work, and you get an NPE (Null Pointer Exception)

Rather always make use of a population - unless you know you will not be using any of those internal functions.

MyAgent name = add_myAgents();

Where myAgents is a population.


问:
Why do you use a Scope Resolution Operator when defining a class' method?
My question about the Scope Resolution Operator (::) is why do we use it in a CPP file to define the methods of a class? I'm more so asking about the SRO itself, rather than the relationship between CPP and Header files.</p>

答:
When you define a class:

```<code>struct foo {
    void bar() {}
};
</code>```

Then the full name of bar is ::foo::bar. The leading :: to refer to the global namespace can often be omitted. There is no bar in the global namespace, hence bar alone (or ::bar) does not name an entity and when you define the method out of line you need to tell what bar you mean:

```<code> struct foo {
       void bar();
 };
 struct baz {
       void bar();
 };

 void bar() {}    // this defines a completely unrelated free function called bar

 void foo::bar() {} // defines foo::bar
 void baz::bar() {} // defines baz::bar
</code>```

You need the scope resolution operator to state which method you want to define.

For more details I refer you to https://en.cppreference.com/w/cpp/language/lookup

Body:
When you define a class:

struct foo {
    void bar() {}
};

Then the full name of bar is ::foo::bar. The leading :: to refer to the global namespace can often be omitted. There is no bar in the global namespace, hence bar alone (or ::bar) does not name an entity and when you define the method out of line you need to tell what bar you mean:

 struct foo {
       void bar();
 };
 struct baz {
       void bar();
 };

 void bar() {}    // this defines a completely unrelated free function called bar

 void foo::bar() {} // defines foo::bar
 void baz::bar() {} // defines baz::bar

You need the scope resolution operator to state which method you want to define.

For more details I refer you to https://en.cppreference.com/w/cpp/language/lookup


问:
What makes the difference in "grad attribute" in the following context?
Consider the following two contexts

```<code>with torch.no_grad():
  params = params - learning_rate * params.grad
</code>```

and

```<code>with torch.no_grad():
  params -= learning_rate * params.grad
</code>```

In the second case .backward() is running smoothly and in the first case it is giving the

```<code>RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
</code>```

What is the reason for this as it is normal to use x-= a and x = x - a interchangeably?

答:
Note that  x -= a and x = x - a cannot be used interchangeably: The latter creates a new tensor that is assigned to the variable x, while the former performes an in place operation.

Therefore with

```<code>with torch.no_grad():
  params -= learning_rate * params.grad
</code>```

everything works fine in your optimization loop, while in

```<code>with torch.no_grad():
  params = params - learning_rate * params.grad
</code>```

the variable params gets overwritten with a new tensor. Since this new tensor was created within a torch.no_grad() context, this means that this new tensor has params.requires_grad=False and therefore does not have a .grad attribute. Therefore in the next iteration torch will complain that params.grad does not exist.

Body:
Consider the following two contexts

with torch.no_grad():
  params = params - learning_rate * params.grad

and

with torch.no_grad():
  params -= learning_rate * params.grad

In the second case .backward() is running smoothly and in the first case it is giving the

RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn

What is the reason for this as it is normal to use x-= a and x = x - a interchangeably?

Body:
Note that  x -= a and x = x - a cannot be used interchangeably: The latter creates a new tensor that is assigned to the variable x, while the former performes an in place operation.

Therefore with

with torch.no_grad():
  params -= learning_rate * params.grad

everything works fine in your optimization loop, while in

with torch.no_grad():
  params = params - learning_rate * params.grad

the variable params gets overwritten with a new tensor. Since this new tensor was created within a torch.no_grad() context, this means that this new tensor has params.requires_grad=False and therefore does not have a .grad attribute. Therefore in the next iteration torch will complain that params.grad does not exist.


问:
How to register custom field that is based on existing value in REST route
Iam registering a rest route (see Code 1) whereby the content of the route  will be equal to results from the wpso_messages database.

The resultant JSON of the get request to the custom route is below. (see #Resultant Json)

I would like to register 2 additional custom fields in the rest route which are:  <username_from> and <username_to> that are based on the login names of the userids currently defined in the  <user_from> and <user_to> (see Resultant JSON).

I understand that I may have to use register rest field function (see sample code 2), however it doesnt seem to be getting hooked to the registered custom rest route, also, I would need to access the user_from column in the existing api callback.

Any advise?

#Code 1: Register Rest Route

```<code><?php

 function get_wp_query() {
    global $wpdb;
      $row = $wpdb->get_results("SELECT * FROM wpso_messages");
      return $row;
      };
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );
</code>```

#Resultant JSON

{
"id": "1",
"user_from": "82",
"user_to": "1",
"created_at": "2022-01-07 10:25:56",
"message": "Iam interest to bid",
"listing_id": "22775",
"seen": "1"
}

Code 2:

```<code>function get_custom_fields() {
    return 'our awesome endpoint';
}
add_action( 'rest_api_init', 'add_custom_fields' );

function add_custom_fields() {
    register_rest_field(
        'messages',
        'custom_fields', //New Field Name in JSON RESPONSEs
        array(
            'get_callback'    => 'get_custom_fields', // custom function name
            'update_callback' => null,
            'schema'          => null,
            )
        );
    }
</code>```

答:
Solution based Nawaz proposal:</p>
```<code>function get_wp_query() {
    global $wpdb;
    $rows = $wpdb->get_results("SELECT * FROM wpso_messages");
    foreach( $rows as $index => $row ) {

           $user_from_id = $rows[$index]->user_from;
           $user_to_id = $rows[$index]->user_to;
           $rows[$index]->username_from = get_user_by('id', $user_from_id)->display_name;
           $rows[$index]->username_to = get_user_by('id', $user_to_id)->display_name;
    }
    return $rows;
};

add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );
</code>```

Body:
Iam registering a rest route (see Code 1) whereby the content of the route  will be equal to results from the wpso_messages database.

The resultant JSON of the get request to the custom route is below. (see #Resultant Json)

I would like to register 2 additional custom fields in the rest route which are:  <username_from> and <username_to> that are based on the login names of the userids currently defined in the  <user_from> and <user_to> (see Resultant JSON).

I understand that I may have to use register rest field function (see sample code 2), however it doesnt seem to be getting hooked to the registered custom rest route, also, I would need to access the user_from column in the existing api callback.

Any advise?

#Code 1: Register Rest Route

<?php

 function get_wp_query() {
    global $wpdb;
      $row = $wpdb->get_results("SELECT * FROM wpso_messages");
      return $row;
      };
add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );

#Resultant JSON

{
"id": "1",
"user_from": "82",
"user_to": "1",
"created_at": "2022-01-07 10:25:56",
"message": "Iam interest to bid",
"listing_id": "22775",
"seen": "1"
}

Code 2:

function get_custom_fields() {
    return 'our awesome endpoint';
}
add_action( 'rest_api_init', 'add_custom_fields' );

function add_custom_fields() {
    register_rest_field(
        'messages',
        'custom_fields', //New Field Name in JSON RESPONSEs
        array(
            'get_callback'    => 'get_custom_fields', // custom function name
            'update_callback' => null,
            'schema'          => null,
            )
        );
    }

Body:
Solution based Nawaz proposal:

function get_wp_query() {
    global $wpdb;
    $rows = $wpdb->get_results("SELECT * FROM wpso_messages");
    foreach( $rows as $index => $row ) {

           $user_from_id = $rows[$index]->user_from;
           $user_to_id = $rows[$index]->user_to;
           $rows[$index]->username_from = get_user_by('id', $user_from_id)->display_name;
           $rows[$index]->username_to = get_user_by('id', $user_to_id)->display_name;
    }
    return $rows;
};

add_action( 'rest_api_init', function () {
    register_rest_route( 'wp/v2', 'messages', array(
        'methods' => 'GET',
        'callback' => 'get_wp_query'
        ) );
    } );


问:
Add New Result Below The Result of Mysql Select
This my table

This what I want

Its gonna be easy if we use php, but I want to know, is it possible with query?

答:
Select * from table where kode in (Select group_concat(id) as ids from table where kode=0)
Order by kode asc

you can try with this type of query


问:
Remove product title when product is "out of stock" on WooCommerce shop and archives pages
I am running an art gallery website using WooCommerce and the owner does not want to show the product name/title if the product has been sold/out of stock.

I have got this far with putting together a function, but it doesn't work. I wondered if anyone could give me any tips?

// Hides title on Sold products
add_filter( 'woocommerce_shop_loop_item_title', 'remove_name', 10, 2 );
function remove_name ( $product ) {
    if ( ! $product->is_in_stock()) {
        $title = '';
    }
    return $title;
}
```

答:
Please try to use this hook to remove product title. Use this inside the condition to check if product is in stock:</p>
```<code>remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );
</code>```

Body:
Please try to use this hook to remove product title. Use this inside the condition to check if product is in stock:

remove_action( 'woocommerce_shop_loop_item_title','woocommerce_template_loop_product_title', 10 );


问:
How can I make it so only the tab area loads instead of the page jumping to the top after clicking on tab?
As the title states, I'm making a tabbed section to switch content upon click which works fine, how can I make it so upon clicking a new tab it has a smooth transition to the content as well as prevent jumping to the top of the page every time I click a tab?

I've tried adding the function which prevents it for links but this isn't a link so that doesn't seem to be working.

HTML

```<code> <section class="featured-books">
        <div class="featured-books-title"><h2>Featured Books</h2></div>
        <ul class="tabs">
            <li data-tab-target="#featured" class="active tab">Featured</li>
            <li data-tab-target="#on-sale" class="tab">On Sale</li>
            <li data-tab-target="#most-viewed" class="tab">Most Viewed</li>
        </ul>
        <div id="featured" data-tab-content class="active">
            <div class="featured-tab">
                <img src="./images/12-rules.jpg">
                <img src="./images/7-habits.jpg">
                <img src="./images/art-of-war.jpg">
                <img src="./images/boundaries.jpg">
                <img src="./images/unlimited-memory.jpg">
                <img src="./images/meaning-of-marriage.jpg">
                <img src="./images/meditations.jpg">
                <img src="./images/peaceful-parents.jpg">
                <img src="./images/plant-paradox.jpg">
                <img src="./images/spirit-filled-life.jpg">
                <img src="./images/javascript-definitive-guide.jpg">
                <img src="./images/atomic-habits.jpg">
            </div>
        </div>
        <div id="on-sale" data-tab-content>
        </div>
        <div id="most-viewed" data-tab-content>
        </div>
    </section>
</code>```

CSS

```<code>.featured-books h1 {
    display: flex;
    justify-content: center;
}

[data-tab-content] {
    display: none;
}

.active[data-tab-content] {
    display: block;
}

.tabs {
    display: flex;
    justify-content: center;
    list-style-type: none;
    margin: 0;
    padding-bottom: 60px;
    padding-top: 16px;
}

.tab {
    border-radius: 20px;
    cursor: pointer;
    padding: 10px;
}

.tab.active {
    background-color: #CCC;
}

.tab:hover {
    background-color: #aaa;
}

/**------FEATURED TAB CONTENT------*/

.featured-tab {
    position: absolute;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
    width: 100vw;
    display: grid;
    grid-template-columns: repeat(auto-fill,minmax(300px,300px));
    column-gap: 3px;
    row-gap: 40px;
  }

  .featured-tab img {
    width: 180px;
    height: auto;
    object-fit: cover;
    object-position: center;
  }
</code>```

JavaScript

```<code>const tabContents = document.querySelectorAll('[data-tab-content]')

  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      const target = document.querySelector(tab.dataset.tabTarget)
      tabContents.forEach(tabContent => {
      tabContent.classList.remove('active')
    })
    tabs.forEach(tab => {
      tab.classList.remove('active')
    })
    tab.classList.add('active')
    target.classList.add('active')
  })
})
</code>```

答:
Here is a simple example using a opacity transition but you can use height, width or transform if you would like. I use aria-attributes to keep track of things like which article is open and if the information in the article should be picked up by screen readers. The two most important CSS classes are show and hide. These control the opacity and when the transition takes place.  Show has a slight delay so it waits for the one being hidden to get out of the way. As far as the JavaScript.

Select all the buttons that have popups.

Create a event listener to handle the click.

Select the controlled article and all the articles.

Check if the controlled article is currently hidden.

If it is hide all the artiles.

Change all the buttons aria-expanded attributes to false.

Set the aria-expanded attribute on the clicked button to true.

Set aria-hidden class on the controlled article to false.

Remove the hide class and add the show class to the controlled article.

const buttons = document.querySelectorAll("[aria-haspopup=true]")

const handleClick = (event) => {
  const controls = event.target.getAttribute("aria-controls"),
  controlled = document.getElementById(controls),
  articles = document.querySelectorAll("article");
  if (controlled.getAttribute("aria-hidden") === "true") {
    articles.forEach(article => {
      article.setAttribute("aria-hidden", "true");
      article.classList.add("hide");
      article.classList.remove("show");
    })
    buttons.forEach(button => button.setAttribute("aria-expanded", "false"))
    event.target.setAttribute("aria-expanded", "true");
    controlled.setAttribute("aria-hidden", "false");
    controlled.classList.remove("hide");
    controlled.classList.add("show");
  }
}

buttons.forEach(button => {
  button.addEventListener("click", handleClick);
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
}

li {
  margin-right: 10px;
}

article {
  height: calc(100vh - 50px);
  width: 100vw;
  position: absolute;
  top: 50px;
  left: 0;
}

#feature {
  background-color: red;
}

#sale {
  background-color: green;
}

#view {
  background-color: blue;
}

.show {
  opacity: 1;
  transition: opacity .2s ease-in-out .2s;
}

.hide {
  opacity: 0;
  transition: opacity .2s ease-in-out;
}

button[aria-expanded=true] {
  background-color:  #cceeff;
}</code>```

    <button aria-haspopup="true" aria-expanded="true" aria-controls="feature">Featured</button>

    <button aria-haspopup="true" aria-expanded="false" aria-controls="sale">On Sale</button>

    <button aria-haspopup="true" aria-expanded="false" aria-controls="view">Most Viewed</button>

Featured

On Sale

Most Viewed

```

Body:
As the title states, I'm making a tabbed section to switch content upon click which works fine, how can I make it so upon clicking a new tab it has a smooth transition to the content as well as prevent jumping to the top of the page every time I click a tab?

I've tried adding the function which prevents it for links but this isn't a link so that doesn't seem to be working.

HTML

Featured Books

Featured

On Sale

Most Viewed

CSS

.featured-books h1 {
    display: flex;
    justify-content: center;
}

[data-tab-content] {
    display: none;
}

.active[data-tab-content] {
    display: block;
}

.tabs {
    display: flex;
    justify-content: center;
    list-style-type: none;
    margin: 0;
    padding-bottom: 60px;
    padding-top: 16px;
}

.tab {
    border-radius: 20px;
    cursor: pointer;
    padding: 10px;
}

.tab.active {
    background-color: #CCC;
}

.tab:hover {
    background-color: #aaa;
}

/**------FEATURED TAB CONTENT------*/

.featured-tab {
    position: absolute;
    justify-content: center;
    align-items: center;
    margin-top: 10px;
    width: 100vw;
    display: grid;
    grid-template-columns: repeat(auto-fill,minmax(300px,300px));
    column-gap: 3px;
    row-gap: 40px;
  }

  .featured-tab img {
    width: 180px;
    height: auto;
    object-fit: cover;
    object-position: center;
  }

JavaScript

const tabContents = document.querySelectorAll('[data-tab-content]')

  tabs.forEach(tab => {
    tab.addEventListener('click', () => {
      const target = document.querySelector(tab.dataset.tabTarget)
      tabContents.forEach(tabContent => {
      tabContent.classList.remove('active')
    })
    tabs.forEach(tab => {
      tab.classList.remove('active')
    })
    tab.classList.add('active')
    target.classList.add('active')
  })
})

Body:
Here is a simple example using a opacity transition but you can use height, width or transform if you would like. I use aria-attributes to keep track of things like which article is open and if the information in the article should be picked up by screen readers. The two most important CSS classes are show and hide. These control the opacity and when the transition takes place.  Show has a slight delay so it waits for the one being hidden to get out of the way. As far as the JavaScript.

Select all the buttons that have popups.

Create a event listener to handle the click.

Select the controlled article and all the articles.

Check if the controlled article is currently hidden.

If it is hide all the artiles.

Change all the buttons aria-expanded attributes to false.

Set the aria-expanded attribute on the clicked button to true.

Set aria-hidden class on the controlled article to false.

Remove the hide class and add the show class to the controlled article.

const buttons = document.querySelectorAll("[aria-haspopup=true]")

const handleClick = (event) => {
  const controls = event.target.getAttribute("aria-controls"),
  controlled = document.getElementById(controls),
  articles = document.querySelectorAll("article");
  if (controlled.getAttribute("aria-hidden") === "true") {
    articles.forEach(article => {
      article.setAttribute("aria-hidden", "true");
      article.classList.add("hide");
      article.classList.remove("show");
    })
    buttons.forEach(button => button.setAttribute("aria-expanded", "false"))
    event.target.setAttribute("aria-expanded", "true");
    controlled.setAttribute("aria-hidden", "false");
    controlled.classList.remove("hide");
    controlled.classList.add("show");
  }
}

buttons.forEach(button => {
  button.addEventListener("click", handleClick);
})

ul {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
}

li {
  margin-right: 10px;
}

article {
  height: calc(100vh - 50px);
  width: 100vw;
  position: absolute;
  top: 50px;
  left: 0;
}

#feature {
  background-color: red;
}

#sale {
  background-color: green;
}

#view {
  background-color: blue;
}

.show {
  opacity: 1;
  transition: opacity .2s ease-in-out .2s;
}

.hide {
  opacity: 0;
  transition: opacity .2s ease-in-out;
}

button[aria-expanded=true] {
  background-color:  #cceeff;
}

<ul>
  <li>
    <button aria-haspopup="true" aria-expanded="true" aria-controls="feature">Featured</button>
  </li>
  <li>
    <button aria-haspopup="true" aria-expanded="false" aria-controls="sale">On Sale</button>
  </li>
  <li>
    <button aria-haspopup="true" aria-expanded="false" aria-controls="view">Most Viewed</button>
  </li>
</ul>
<article class="show" id="feature" aria-hidden="false">
  <h1>Featured</h1>
</article>
<article class="hide" id="sale" aria-hidden="true">
  <h1>On Sale</h1>
</article>
<article class="hide" id="view" aria-hidden="true">
  <h1>Most Viewed</h1>
</article>


问:
Enable access to AWS security group from Google Cloud project
I host my database with AWS on an RDS MySQL instance.

I would like to give all instances I create in a specific Google Cloud project to be whitelisted for the RDS security group.

Is this possible?

答:
If you have only couple of instances, you can grant them public, static IPs - (1).  It can be new IPs or you can promote those they already have.

If you have or expect many instances to interact with AWS, you should consider NAT  (2) or VPN Interconnect (3) as suggested by @jarmod.

There are also Dedicated Interconnect (4) and Partner Interconnect (5) options.

Remember to check the estimated cost in Pricing calculator before commiting to any of the options.


问:
Which operations in numpy uses SIMD?
Good afternoon!
Currently, I'm diggin out the reason why numpy is fast.
More specific, I'm wondering why np.sum() is that fast.
My one suggestion is np.sum() uses some kind of SIMD optimization, but I'm not sure whether it is.
Is there any way that I can check which numpy's method uses SIMD operations?
Thx in advance</p>

答:
Numpy does not currently use SIMD instructions for trivial np.sum calls yet. However, I made this PR which should be merged soon and fix this issue with integers (it will use the 256-bit AVX2 instruction set if available and the 128-bit SSE/Neon instruction set otherwise). Using SIMD instructions for np.sum with floating-point numbers is a bit harder due to the current algorithm used (pair-wise summation) and because one should care about the precision.

Is there any way that I can check which numpy's method uses SIMD operations?

Low-level profilers and hardware-counter-based tools (eg. Linux perf, Intel VTune) can do that but they are not very user-friendly (ie. you need to have some notions in assembly, know roughly how processors work and read some documentation about hardware counters). Another solution is to look the disassembled code of Numpy using tools like objdump (require a pretty good knowledge in assembly and the name of the C function called) or simply look at the Numpy C code (note compilers can autovectorize loops so this solution is not so simple).

Update: If you are using np.sum on contiguous double-precision Numpy arrays, then the benefit of using SIMD instructions is not so big. Indeed, for large contiguous double-precision arrays not fitting in the cache, a scalar implementation should be able to saturate the memory bandwidth on most PCs (but certainly not the Apple M1 nor computing servers), especially on high-frequency processors. On small arrays (eg. <4000), Numpy overheads dominate the execution time of such a function. For contiguous medium-sized arrays (eg. >10K and <1M items), using SIMD instructions should result in a significant speed up, especially for simple-precision arrays (eg. 3-4 times faster on DP and 6-8 times faster on SP on mainstream machines).

Title: Which operations in numpy uses SIMD?


问:
Slow installation time with pip on raspberry pi

Have anyone else experience slow installation times with pip on a raspberry pi?

After I installed python3.8 on my pi, it takes ages to install packages.
Can anyone see any mistakes in my installation process?

sudo apt update
sudo apt upgrade -y
# build tools
sudo apt install build-essential zlib1g-dev libncurses5-dev\
 libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev curl

# SSL certificate
sudo apt-get install libssl-dev
```
<pre class="lang-sh prettyprint-override"><code>wget https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tar.xz
</code>```
```<code>tar -xf Python-3.8.6.tar.xz
cd Python-3.8.6
./configure
sudo make install
</code>```

Then I checked my install by running:

```<code>python3 -m test
</code>```

Updated pip

```<code>python3.8 -m pip install -U pip
</code>```

And now it takes ages to install the package steinloss which I don't understand

python3.8 -m pip install steinloss
```

答:
Building from source can take forever in a Raspberry in some cases, you can use precompiled binaries form piwheel

Check if /etc/pip.conf has the following configuration

```<code>>     [global]
>     extra-index-url=https://www.piwheels.org/simple
</code>```

You can find more info on https://www.piwheels.org/

NOTE: Piwheel has precompiled binaries up to Python 3.9

Body:
Have anyone else experience slow installation times with pip on a raspberry pi?

After I installed python3.8 on my pi, it takes ages to install packages.
Can anyone see any mistakes in my installation process?

sudo apt update
sudo apt upgrade -y
# build tools
sudo apt install build-essential zlib1g-dev libncurses5-dev\
 libgdbm-dev libnss3-dev libssl-dev libreadline-dev libffi-dev curl

# SSL certificate
sudo apt-get install libssl-dev

wget https://www.python.org/ftp/python/3.8.6/Python-3.8.6.tar.xz

tar -xf Python-3.8.6.tar.xz
cd Python-3.8.6
./configure
sudo make install

Then I checked my install by running:

python3 -m test

Updated pip

python3.8 -m pip install -U pip

And now it takes ages to install the package steinloss which I don't understand

python3.8 -m pip install steinloss

Body:
Building from source can take forever in a Raspberry in some cases, you can use precompiled binaries form piwheel

Check if /etc/pip.conf has the following configuration

>     [global]
>     extra-index-url=https://www.piwheels.org/simple

You can find more info on https://www.piwheels.org/

NOTE: Piwheel has precompiled binaries up to Python 3.9


问:
Nondeterministic Algorithms
I need a simple description of nondeterministic algorithms . Can we comapre nondeterministic algorithm with computer with parrallel processor?
please someone exactly explain me about nondeterministic algorithms</p>

答:
a non deterministic algorithm is an algorithm ran on a non deterministic turing machine.

each calculation in this algorithm can branch into 2 calculations, which are computed simultaneously.

none deterministic algorithm example:

Set Cover: "guess" a subset of the vertices, and check if it is a valid cover.

the guessing is: for each element: check one possibility it IS in the set and it is NOT in the set.

It is not parallel processor, because in here (nondeterministic algorithm), the number of branches is not limited, while in parallel processor it is. In parallel computing, you are still bounded to do the 2^n OPs for finding vertex coverage, while in nondeterministic algorithm, you are doing only n ops, with n different branches.

a non-deterministic machine would be more like quantum computer, than parallel processing. [note that quantum computer is still 'weaker' then non-deterministic turing machine, assuming P!=NP, of course].

Title: Nondeterministic Algorithms


问:
Host a Django project on Apache2 locally
I have finished a Django project and want to deploy it over Apache2 locally over LAN. I have figured out how to connect Django with Apache2 using mod_wsgi and it worked great because I was able to use Apace2 to actually host Django on localhost.
Now I want to actually make this project available to anyone on my local network. Like for instance assuming that my local IP address was 10.10.10.51 I could go to a different device connected to my local network and type in 10.10.10.51 to actually get to the Apache2 server homepage. It does that successfully.
My Django project is hosted on my Apache2 localhost server at djangoproject.localhost and it works fine just on my PC. When I move on to the other PC and go to djangoproject.localhost the site is not up there. Yes they are both connected to the same LAN network.
I used this tutorial to host Django on Apache2: Host Django on Apache2 with mod_wsgi</p>

答: I think that you have to configure something called port forwarding in your home modem, this video could help: https://www.youtube.com/watch?v=6gkoDQUQSLc</p>


问:
How to convert this firebase code into its latest syntax in React.js?
```<code>useEffect(() => {
  db.collection('posts').onSnapshot((snapshot) => {
    setPosts(snapshot.docs.map((doc) => doc.data()));
  });
}, []);
</code>```

I have been trying to use this code in react but I was unable to do it.

答:
From the docs</p>
```<code>import { doc, onSnapshot, getFirestore } from "firebase/firestore";
db = getFirestore();

const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
    console.log("Current data: ", doc.data());
});
</code>```

Body:
useEffect(() => {
  db.collection('posts').onSnapshot((snapshot) => {
    setPosts(snapshot.docs.map((doc) => doc.data()));
  });
}, []);

I have been trying to use this code in react but I was unable to do it.

Body:
From the docs

import { doc, onSnapshot, getFirestore } from "firebase/firestore";
db = getFirestore();

const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
    console.log("Current data: ", doc.data());
});


问:
if [ $inst != "GPS" && $inst != "USRP" ] results in error: missing `]'
```<code>if [ $inst != "GPS" && $inst != "USRP" && $inst != "GCSM" &&  $inst != "EFMS" && $inst != "instAR" && $inst != "CRF" && $inst != "DBOR" && $inst != "PAL"     &&  $inst != "GRDB" && $inst != "GIOM" && $inst != "FA" && $inst != "WS" ]
then
    help
fi
</code>```

Error message:

```<code>30: [: missing `]'
</code>```

What does this mean and how do I fix it?

答:
The syntax you are trying to use is quite unwieldy anyway. May I suggest you switch to a case statement instead?

```<code>case $inst in
  GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)
    ;;
  *)
    help
  ;;
esac
</code>```

The punctuation-heavy syntax of this statement may be jarring at first, but you should find that it is a lot more robust and versatile than the clunky if.

Body:
if [ $inst != "GPS" && $inst != "USRP" && $inst != "GCSM" &&  $inst != "EFMS" && $inst != "instAR" && $inst != "CRF" && $inst != "DBOR" && $inst != "PAL"     &&  $inst != "GRDB" && $inst != "GIOM" && $inst != "FA" && $inst != "WS" ]
then
    help
fi

Error message:

30: [: missing `]'

What does this mean and how do I fix it?

Body:
The syntax you are trying to use is quite unwieldy anyway. May I suggest you switch to a case statement instead?

case $inst in
  GPS|USRP|GCSM|EFMS|instAR|CRF|DBOR|PAL|GRDB|GIOM|FA|WS)
    ;;
  *)
    help
  ;;
esac

The punctuation-heavy syntax of this statement may be jarring at first, but you should find that it is a lot more robust and versatile than the clunky if.


问:
Extract text from a series into new columns
I've tries the following code with the following error message:

AttributeError: 'DataFrame' object has no attribute 'str'

I'm referencing a string series, then why am i getting a "Dataframe" error?

```<code>df['PO'] =  df['extract'].str.extract(r"(?:^(?=[A-Z\d/-]+$)|\bPO\W*)([A-Z\d/-]+)")
</code>```

答:
Problem is with duplicated columns names, so if select one column extract get all columns in DataFrame.

```<code>print (df['extract'])
</code>```

For deduplicted is simpliest set columns names or some another solution:

```<code>df.columns= ['a','b']
</code>```

Body:
I've tries the following code with the following error message:

AttributeError: 'DataFrame' object has no attribute 'str'

I'm referencing a string series, then why am i getting a "Dataframe" error?

df['PO'] =  df['extract'].str.extract(r"(?:^(?=[A-Z\d/-]+$)|\bPO\W*)([A-Z\d/-]+)")

Body:
Problem is with duplicated columns names, so if select one column extract get all columns in DataFrame.

print (df['extract'])

For deduplicted is simpliest set columns names or some another solution:

df.columns= ['a','b']


问:
How to create this chart in R or ggplot
Below is the code to create the data frame.

```<code>df <- data.frame (ID  = c('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'),
                  A = c(1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2),
                  B = c(3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2)
                  )
</code>```

Code to create the Category column:

```<code>df$Cat <- ifelse(df$A == 2 & df$B == 2, 'MID',
                 ifelse(df$A == 2 & df$B == 1, 'GONE',
                        ifelse(df$A == 1 & df$B == 1, 'GONE',
                               ifelse(df$A == 1 & df$B == 2, 'GONE',
                                      ifelse(df$A == 2 |df$A == 1 & df$B == 3, 'UP',

                               'NO')))))
</code>```

The chart I need to create:

How can I create the chart I want from the data above? I have tried using Treemaps for this but I don't think that will work because it only allows comparing quantities by size in a fixed space. So what can be used? Any help will be greatly appreciate

答:
Try a heatmap with ggplot2 using geom_tile()

```<code>ggplot(df, aes(A, B, fill= Cat)) +
  geom_tile() +
  scale_fill_manual(values = c("blue", "green", "red")) +
  geom_text(aes(label = Cat), size=5)
</code>```

Title: How to create this chart in R or ggplot

Body:
Below is the code to create the data frame.

df <- data.frame (ID  = c('C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9','C10', 'C11', 'C12','C13', 'C14'),
                  A = c(1, 1, 2, 2, 2, 1, 1, 1, 2, 1, 1, 2, 2, 2),
                  B = c(3, 3, 1, 1, 1, 1, 1, 2, 3, 3, 2, 2, 2, 2)
                  )

Code to create the Category column:

df$Cat <- ifelse(df$A == 2 & df$B == 2, 'MID',
                 ifelse(df$A == 2 & df$B == 1, 'GONE',
                        ifelse(df$A == 1 & df$B == 1, 'GONE',
                               ifelse(df$A == 1 & df$B == 2, 'GONE',
                                      ifelse(df$A == 2 |df$A == 1 & df$B == 3, 'UP',

                               'NO')))))

The chart I need to create:

How can I create the chart I want from the data above? I have tried using Treemaps for this but I don't think that will work because it only allows comparing quantities by size in a fixed space. So what can be used? Any help will be greatly appreciate

Body:
Try a heatmap with ggplot2 using geom_tile()

ggplot(df, aes(A, B, fill= Cat)) +
  geom_tile() +
  scale_fill_manual(values = c("blue", "green", "red")) +
  geom_text(aes(label = Cat), size=5)


问:
Is there any particular difference between intval and casting to int - `(int) X`?
Is there any particular difference between intval and (int)?

Example:

```<code>$product_id = intval($_GET['pid']);
$product_id = (int) $_GET['pid'];
</code>```

Is there any particular difference between above two lines of code?

答:
Amber is right and if I may add a useful information
type casting (adding a "(int)" before your expression ) is 300 to 600% faster than intval.
So if your purpose is not to dealing with other bases than decimal, I recommend using:
 (int) $something

Body:
Is there any particular difference between intval and (int)?

Example:

$product_id = intval($_GET['pid']);
$product_id = (int) $_GET['pid'];

Is there any particular difference between above two lines of code?


问:
Is there a way to get all combinations of overlap between values in dictionary, or from within a list
I have a few lists

```<code>A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']
</code>```

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

```<code>my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}
</code>```

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

```<code>   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))
</code>```

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

```<code>   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC
</code>```

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

答:
Here is the dictionary creation with the answer of @Marco Breemhaar implemented, and I used his solution to create a dictionary as you wanted. Here is the code:</p>
```<code>import itertools

import string
alphabet_string = string.ascii_uppercase
alphabet_list = list(alphabet_string)

A =['D','KIT','SAP']
B= ['F','G','LUFT','SAP']
C= ['I','SAP']
D= ['SAP','LUF','KIT']
E= ['SAP','LUF','KIT','HASS']

lists = [A, B, C, D, E]

combinations = []

for l in range(2, len(lists) + 1):
    combinations += itertools.combinations(lists, l)

alp_comb = []
for l in range(2, len(alphabet_list) + 1):
    alp_comb += itertools.combinations(alphabet_list[:len(lists)], l)

key_list = []
for alp_elem in alp_comb:
    key_name = ""
    for elem in alp_elem:
        key_name += elem
    key_list.append(key_name)
    key_name = None

res_dict = dict()
for key, elem in zip(key_list, combinations):
    res_dict[key] = list(elem)
print(res_dict)
</code>```

Body:
I have a few lists

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

Body:
Here is the dictionary creation with the answer of @Marco Breemhaar implemented, and I used his solution to create a dictionary as you wanted. Here is the code:

import itertools

import string
alphabet_string = string.ascii_uppercase
alphabet_list = list(alphabet_string)

A =['D','KIT','SAP']
B= ['F','G','LUFT','SAP']
C= ['I','SAP']
D= ['SAP','LUF','KIT']
E= ['SAP','LUF','KIT','HASS']

lists = [A, B, C, D, E]

combinations = []

for l in range(2, len(lists) + 1):
    combinations += itertools.combinations(lists, l)

alp_comb = []
for l in range(2, len(alphabet_list) + 1):
    alp_comb += itertools.combinations(alphabet_list[:len(lists)], l)

key_list = []
for alp_elem in alp_comb:
    key_name = ""
    for elem in alp_elem:
        key_name += elem
    key_list.append(key_name)
    key_name = None

res_dict = dict()
for key, elem in zip(key_list, combinations):
    res_dict[key] = list(elem)
print(res_dict)


问:
Autowire CacheManger (Caffeine & Ehcache) without using @SpringBootApplication
I have a common caching module which has spring boot starter cache (version 2.2.4.RELEASE) and for caching has dependencies of ehcache & caffeine. Below is the pom file

```<code>    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
</dependencies>
</code>```

In this module, Autowired the CacheManger and has cache update & get method using spring cache.

```<code>@Autowired
private CacheManager cacheManager;
</code>```

This module is added as dependency in the app1 which is springboot application and as per the property "spring.cache.type", when app1 starts it will initialize the respective cache

For caffeine cache

```<code>spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=10000
</code>```

For Ehcache3

```<code>spring.cache.type=caffeine
spring.cache.jcache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.cache.jcache.config=classpath:ehcache.xml
</code>```

This is all working fine for springboot application app1.

Now i am using the same caching module in app2 which has functionality same as app1 but it is not springboot application. In app2 using @Configuration , @ComponentScan to resolve the dependency. Now app2 is being used in app3 which is springboot application. All the other dependencies are resolved and working fine in app3 except the cacheManger. Getting the below error while running the app3

```<code>*\r\nAPPLICATION FAILED TO START\r\n***************************\r\n\r\nDescription:\r\n\r\nField cacheManager in commonCacheService required a bean of type 'org.springframework.cache.CacheManager' that could not be found.\r\n\r\nThe injection point has the following annotations:\r\n\t- @org.springframework.beans.factory.annotation.Autowired(required=true)\r\n\r\nThe following candidates were found but could not be injected:\r\n\t- Bean method 'cacheManager' in 'EhCacheCacheConfiguration' not loaded because @ConditionalOnClass did not find required class 'net.sf.ehcache.Cache'\r\n\t- Bean method 'cacheManager' in 'GenericCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'JCacheCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'NoOpCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'SimpleCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration unknown cache type\r\n\r\n\r\nAction:\r\n\r\nConsider revisiting the entries above or defining a bean of type 'org.springframework.cache.CacheManager' in your configuration.\r\n"}
</code>```

It is working if i create bean in common cache module like below

```<code>@Bean
@ConditionalOnProperty(name="spring.cache.type", havingValue="caffeine")
@Primary
public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    cacheManager.setCaffeine(Caffeine.newBuilder().maximumSize(125000));
    return cacheManager;
}
</code>```

But i want to avoid the bean creation in common module. Is there any annotation/configuration required in app2 (without changing app3 as don't have any update control on app3)so that it will also work in same way as it is working in app1 )?

答:
I know it is quite late, but I faced the same issue. It was resolved by adding dependency

```<code><dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>javax.cache</groupId>
     <artifactId>cache-api</artifactId>
     <version>1.1.1</version>
</dependency>
</code>```

And add

@EnableCaching

in the SpringBootApplciation Class

Body:
I have a common caching module which has spring boot starter cache (version 2.2.4.RELEASE) and for caching has dependencies of ehcache & caffeine. Below is the pom file

    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-cache</artifactId>
    </dependency>

    <dependency>
        <groupId>javax.cache</groupId>
        <artifactId>cache-api</artifactId>
    </dependency>
    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>com.github.ben-manes.caffeine</groupId>
        <artifactId>caffeine</artifactId>
    </dependency>
</dependencies>

In this module, Autowired the CacheManger and has cache update & get method using spring cache.

@Autowired
private CacheManager cacheManager;

This module is added as dependency in the app1 which is springboot application and as per the property "spring.cache.type", when app1 starts it will initialize the respective cache

For caffeine cache

spring.cache.type=caffeine
spring.cache.caffeine.spec=maximumSize=10000

For Ehcache3

spring.cache.type=caffeine
spring.cache.jcache.provider=org.ehcache.jsr107.EhcacheCachingProvider
spring.cache.jcache.config=classpath:ehcache.xml

This is all working fine for springboot application app1.

Now i am using the same caching module in app2 which has functionality same as app1 but it is not springboot application. In app2 using @Configuration , @ComponentScan to resolve the dependency. Now app2 is being used in app3 which is springboot application. All the other dependencies are resolved and working fine in app3 except the cacheManger. Getting the below error while running the app3

*\r\nAPPLICATION FAILED TO START\r\n***************************\r\n\r\nDescription:\r\n\r\nField cacheManager in commonCacheService required a bean of type 'org.springframework.cache.CacheManager' that could not be found.\r\n\r\nThe injection point has the following annotations:\r\n\t- @org.springframework.beans.factory.annotation.Autowired(required=true)\r\n\r\nThe following candidates were found but could not be injected:\r\n\t- Bean method 'cacheManager' in 'EhCacheCacheConfiguration' not loaded because @ConditionalOnClass did not find required class 'net.sf.ehcache.Cache'\r\n\t- Bean method 'cacheManager' in 'GenericCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'JCacheCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'NoOpCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration unknown cache type\r\n\t- Bean method 'cacheManager' in 'SimpleCacheConfiguration' not loaded because Cache org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration unknown cache type\r\n\r\n\r\nAction:\r\n\r\nConsider revisiting the entries above or defining a bean of type 'org.springframework.cache.CacheManager' in your configuration.\r\n"}

It is working if i create bean in common cache module like below

@Bean
@ConditionalOnProperty(name="spring.cache.type", havingValue="caffeine")
@Primary
public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager();
    cacheManager.setCaffeine(Caffeine.newBuilder().maximumSize(125000));
    return cacheManager;
}

But i want to avoid the bean creation in common module. Is there any annotation/configuration required in app2 (without changing app3 as don't have any update control on app3)so that it will also work in same way as it is working in app1 )?

Body:
I know it is quite late, but I faced the same issue. It was resolved by adding dependency

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>javax.cache</groupId>
     <artifactId>cache-api</artifactId>
     <version>1.1.1</version>
</dependency>

And add

@EnableCaching

in the SpringBootApplciation Class