问:
Problem in implementation of synchronization between producer and consumer using semaphores
Like everyone I was trying to understand linux OS better. I was implementing the producer consumer synchronization problem using semaphores.

i)There will be m producer processes and n consumer processes.

ii) A product is presented with a random number.

iii) The buffer is shared between all consumer and producer processes while in variable is shared between all producer processes and out variable is shared between all consumer processes.

iv)All processes will stop once CTRL+C is entered in the terminal.

Here are the codes:

1.shared.h

```<code>//assume all required headers included
#define buffer_size 5
#define empty_id 0
#define full_id 1
#define mutex_id 2
#define no_sem 3

struct sembuf signall = {0 , 1, 0};
struct sembuf wait = {0, -1, 0};

#define W(s) semop(s, &wait, 1);
#define S(s) semop(s, &signall, 1);
int shmid;
int *buffer;

union semun
{
                int val;
                struct semid_ds *buf;
                unsigned short  *array;
                struct seminfo  *__buf;

} setvalarg[3];

int *create_shared_mem_buffer()
{
        int *shmaddr;
        key_t key = ftok("/home/******/**/B", 1);
        shmid = shmget(key, buffer_size, IPC_CREAT|0660);
        shmaddr= (int *)shmat(shmid, NULL, 0);
        return shmaddr;
}

void clear_buffer()
{
        int i;
        for(i=0;i<buffer_size;i++)
                buffer[i]=0;
}

void releaseSHM(int signum)
{
        int status;
        clear_buffer();
        status = shmctl(shmid, IPC_RMID, NULL);

        status = kill(0, SIGKILL);
        exit(signum);
}

int create_semaphore_set()
{
        key_t key= ftok("/home/******/**/A", 1);

        int semid= semget(key, no_sem, IPC_CREAT|0600);

        setvalarg[0].val=buffer_size;
        semctl(semid, empty_id, SETVAL, setvalarg[0]);

        setvalarg[1].val=0;
        semctl(semid, full_id, SETVAL, setvalarg[1]);

        setvalarg[2].val=1;
        semctl(semid, mutex_id, SETVAL, setvalarg[2]);
        return semid;
}
</code>```

2.producer.c

```<code>#include "shared.h"

void insert_product(int item, int *in, int *buffer)
{
        *in=(*in+1)%buffer_size;
        buffer[*in]=item;
        printf("Producer produces item %d stored in posn %d  \n",item,*in);
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *in;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);

        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        in=(int *)shmat(shmid1, NULL, 0);
        *in=0;

        int m=5;

        for(i=0;i<m;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                item=rand();
                                wait.sem_num=0;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                insert_product(item, in, buffer);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=1;
                                S(semid);
                                sleep(2); //sleep has been introduced to slowdown the output.
                        }
                }
        }
        return 0;
}
</code>```

consumer.c

```<code>#include "shared.h"

int remove_product(int *out, int *buffer)
{
        int item;
        *out=(*out+1)%buffer_size;
        item=buffer[*out];
        buffer[*out]=0;
        return item;
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *out;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);
        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        out=(int *)shmat(shmid1, NULL, 0);
        *out=-1;

        clear_buffer(buffer);

        int n=2;

        for(i=0;i<n;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                wait.sem_num=1;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                item=remove_product(out, buffer);
                                printf("Consumer consumes the product %d \n", item);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=0;
                                S(semid);
                                sleep(2); //sleep has been introduced to slow down the output
                        }
                }
        }
        return 0;
}
</code>```

The output is somewhat like this:

```<code>Producer produces item 1681692777 stored in posn 2
Producer produces item 1681692777 stored in posn 3
Producer produces item 1681692777 stored in posn 4
Producer produces item 1804289383 stored in posn 1
Producer produces item 1804289383 stored in posn 2
Producer produces item 1804289383 stored in posn 3
Producer produces item 1804289383 stored in posn 0
Producer produces item 1804289383 stored in posn 0
Producer produces item 1681692777 stored in posn 0
Producer produces item 1714636915 stored in posn 1
Producer produces item 1714636915 stored in posn 2
Producer produces item 1714636915 stored in posn 3
Producer produces item 846930886 stored in posn 1
Producer produces item 1714636915 stored in posn 4
Producer produces item 846930886 stored in posn 2
Producer produces item 1714636915 stored in posn 0
Producer produces item 846930886 stored in posn 3
Producer produces item 846930886 stored in posn 4
Producer produces item 846930886 stored in posn 0
Producer produces item 1681692777 stored in posn 1
</code>```

```<code>Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 596516649
Consumer consumes the product 596516649
</code>```

As you can see, the same product is produced more than once and same product is consumed more than once.

i)What is the problem? How to resolve it?

ii) Also the processes donot stop when CTRL+C is entered.

I have done it all by myself and I need someone to review it. If further information needed, drop a comment below.

答:
Here, you fork() into several (five for m=5) processes:

```<code>    for(i=0;i<m;i++)
    {
            pid=fork();
</code>```

and here, you are producing random item numbers:

```<code>            item=rand();
</code>```

but all processes are using the same seed (which is 1, because you did not call srand() before)! So, all forked processes generate the same sequence of random numbers. This is the reason why you add every item 5 times. Try seeding the rng with a different number for each processes, for example by adding an srand() here:

```<code>    for(i=0;i<m;i++)
    {
            srand(m);
            pid=fork();
</code>```

Then, no duplicates should be added.

Body:
Like everyone I was trying to understand linux OS better. I was implementing the producer consumer synchronization problem using semaphores.

i)There will be m producer processes and n consumer processes.

ii) A product is presented with a random number.

iii) The buffer is shared between all consumer and producer processes while in variable is shared between all producer processes and out variable is shared between all consumer processes.

iv)All processes will stop once CTRL+C is entered in the terminal.

Here are the codes:

1.shared.h

//assume all required headers included
#define buffer_size 5
#define empty_id 0
#define full_id 1
#define mutex_id 2
#define no_sem 3

struct sembuf signall = {0 , 1, 0};
struct sembuf wait = {0, -1, 0};

#define W(s) semop(s, &wait, 1);
#define S(s) semop(s, &signall, 1);
int shmid;
int *buffer;

union semun
{
                int val;
                struct semid_ds *buf;
                unsigned short  *array;
                struct seminfo  *__buf;

} setvalarg[3];

int *create_shared_mem_buffer()
{
        int *shmaddr;
        key_t key = ftok("/home/******/**/B", 1);
        shmid = shmget(key, buffer_size, IPC_CREAT|0660);
        shmaddr= (int *)shmat(shmid, NULL, 0);
        return shmaddr;
}

void clear_buffer()
{
        int i;
        for(i=0;i<buffer_size;i++)
                buffer[i]=0;
}

void releaseSHM(int signum)
{
        int status;
        clear_buffer();
        status = shmctl(shmid, IPC_RMID, NULL);

        status = kill(0, SIGKILL);
        exit(signum);
}

int create_semaphore_set()
{
        key_t key= ftok("/home/******/**/A", 1);

        int semid= semget(key, no_sem, IPC_CREAT|0600);

        setvalarg[0].val=buffer_size;
        semctl(semid, empty_id, SETVAL, setvalarg[0]);

        setvalarg[1].val=0;
        semctl(semid, full_id, SETVAL, setvalarg[1]);

        setvalarg[2].val=1;
        semctl(semid, mutex_id, SETVAL, setvalarg[2]);
        return semid;
}

2.producer.c

#include "shared.h"

void insert_product(int item, int *in, int *buffer)
{
        *in=(*in+1)%buffer_size;
        buffer[*in]=item;
        printf("Producer produces item %d stored in posn %d  \n",item,*in);
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *in;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);

        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        in=(int *)shmat(shmid1, NULL, 0);
        *in=0;

        int m=5;

        for(i=0;i<m;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                item=rand();
                                wait.sem_num=0;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                insert_product(item, in, buffer);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=1;
                                S(semid);
                                sleep(2); //sleep has been introduced to slowdown the output.
                        }
                }
        }
        return 0;
}

consumer.c

#include "shared.h"

int remove_product(int *out, int *buffer)
{
        int item;
        *out=(*out+1)%buffer_size;
        item=buffer[*out];
        buffer[*out]=0;
        return item;
}

int shmid1;

int main(int argc, char *argv[])
{
        int i, pid, item;
        int *out;
        buffer = create_shared_mem_buffer();
        int semid= create_semaphore_set();

        sighandler_t shandler;

        shandler =  signal(SIGINT, releaseSHM);
        shmid1=  shmget(IPC_PRIVATE, sizeof(int),IPC_CREAT | 0777);
        out=(int *)shmat(shmid1, NULL, 0);
        *out=-1;

        clear_buffer(buffer);

        int n=2;

        for(i=0;i<n;i++)
        {
                pid=fork();
                if(pid==0)
                {
                        while(1)
                        {
                                wait.sem_num=1;
                                W(semid);
                                wait.sem_num=2;
                                W(semid);
                                item=remove_product(out, buffer);
                                printf("Consumer consumes the product %d \n", item);
                                signall.sem_num=2;
                                S(semid);
                                signall.sem_num=0;
                                S(semid);
                                sleep(2); //sleep has been introduced to slow down the output
                        }
                }
        }
        return 0;
}

The output is somewhat like this:

Producer produces item 1681692777 stored in posn 2
Producer produces item 1681692777 stored in posn 3
Producer produces item 1681692777 stored in posn 4
Producer produces item 1804289383 stored in posn 1
Producer produces item 1804289383 stored in posn 2
Producer produces item 1804289383 stored in posn 3
Producer produces item 1804289383 stored in posn 0
Producer produces item 1804289383 stored in posn 0
Producer produces item 1681692777 stored in posn 0
Producer produces item 1714636915 stored in posn 1
Producer produces item 1714636915 stored in posn 2
Producer produces item 1714636915 stored in posn 3
Producer produces item 846930886 stored in posn 1
Producer produces item 1714636915 stored in posn 4
Producer produces item 846930886 stored in posn 2
Producer produces item 1714636915 stored in posn 0
Producer produces item 846930886 stored in posn 3
Producer produces item 846930886 stored in posn 4
Producer produces item 846930886 stored in posn 0
Producer produces item 1681692777 stored in posn 1

Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 424238335
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 719885386
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 1649760492
Consumer consumes the product 596516649
Consumer consumes the product 596516649
Consumer consumes the product 596516649

As you can see, the same product is produced more than once and same product is consumed more than once.

i)What is the problem? How to resolve it?

ii) Also the processes donot stop when CTRL+C is entered.

I have done it all by myself and I need someone to review it. If further information needed, drop a comment below.

Body:
Here, you fork() into several (five for m=5) processes:

    for(i=0;i<m;i++)
    {
            pid=fork();

and here, you are producing random item numbers:

            item=rand();

but all processes are using the same seed (which is 1, because you did not call srand() before)! So, all forked processes generate the same sequence of random numbers. This is the reason why you add every item 5 times. Try seeding the rng with a different number for each processes, for example by adding an srand() here:

    for(i=0;i<m;i++)
    {
            srand(m);
            pid=fork();

Then, no duplicates should be added.


来源: stackexchange

问:
Azure Function 2.0 Dependency injection error
Before the Azure Function 3.0 my app is working properly but after the Microsoft update. The Function application doesn't work even if I deploy it on Azure it will return the dependency injection error. Why would MS upgrade version that break existing one? I'm really frustrated.

答:
Just reinstall/update the following packages:</p>

```<code><PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.5" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Just reinstall/update the following packages:

<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.5" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.3" />


问:
Web foreground push notification is not popping up integrated using Firebase in Reactjs
I have use fcm for push notification in my reactjs web application. I am able to get notification if the the web application is running in the background. But not able to get notification while my application is actively running in foreground.

Firebase initialization is perfectly done in my project,because I am successfully getting push notification in the background.

firebase-messaging-sw.js

```<code>    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');

    firebase.initializeApp({
      'messagingSenderId': '337889493107'
    });
    const messaging = firebase.messaging();

    messaging.setBackgroundMessageHandler(function (payload) {
      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });
    messaging.onMessage(function(payload) {

      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });
</code>```

Do I need to do any further modification to my foreground method messaging.onMessage or do I need to do any more configuration. Plz help me out

答:
Please try to use Notifications API, instead of the Service Worker API.</p>

```<code>messaging.onMessage(function(payload) {

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon,
    };

    if (!("Notification" in window)) {
        console.log("This browser does not support system notifications.");
    } else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(notificationTitle,notificationOptions);
        notification.onclick = function(event) {
            event.preventDefault();
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }

});
</code>```

Body:
I have use fcm for push notification in my reactjs web application. I am able to get notification if the the web application is running in the background. But not able to get notification while my application is actively running in foreground.

Firebase initialization is perfectly done in my project,because I am successfully getting push notification in the background.

firebase-messaging-sw.js

    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-app.js');
    importScripts('https://www.gstatic.com/firebasejs/6.3.4/firebase-messaging.js');

    firebase.initializeApp({
      'messagingSenderId': '337889493107'
    });
    const messaging = firebase.messaging();

    messaging.setBackgroundMessageHandler(function (payload) {
      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });
    messaging.onMessage(function(payload) {

      const data = JSON.parse(payload.data.notification);
      const notificationTitle = data.title;
      const notificationOptions = {
        body: data.body,
        icon: '/favicon.png'
      };
      return self.registration.showNotification(notificationTitle,
        notificationOptions);
    });

Do I need to do any further modification to my foreground method messaging.onMessage or do I need to do any more configuration. Plz help me out

Body:
Please try to use Notifications API, instead of the Service Worker API.

messaging.onMessage(function(payload) {

    const notificationTitle = payload.notification.title;
    const notificationOptions = {
        body: payload.notification.body,
        icon: payload.notification.icon,
    };

    if (!("Notification" in window)) {
        console.log("This browser does not support system notifications.");
    } else if (Notification.permission === "granted") {
        // If it's okay let's create a notification
        var notification = new Notification(notificationTitle,notificationOptions);
        notification.onclick = function(event) {
            event.preventDefault();
            window.open(payload.notification.click_action , '_blank');
            notification.close();
        }
    }

});


问:
Companion object method not accessible from subclass
I'm trying to use the method getInstance from a subclass.

Any idea why the mentioned method is unaccessible and how to change this code so i can access it?

For the curious mind, this example structure comes from trying to subclass a Room database class on Android.

```<code>open class SingletonHolder<out T: Any, in A>(creator: (A) -> T) {
    private var creator: ((A) -> T)? = creator
    @Volatile private var instance: T? = null

    fun getInstance(arg: A): T {
        val i = instance
        if (i != null) {
            return i
        }

        return synchronized(this) {
            val i2 = instance
            if (i2 != null) {
                i2
            } else {
                val created = creator!!(arg)
                instance = created
                creator = null
                created
            }
        }
    }
}

abstract class subclass(val par: Int): superclass(par) {
    abstract fun function1()
}

class subclass_Impl(val par1: Int): subclass(par1) {
    override fun function1() {
        Log.d("unused", "unused")
    }

    override fun f2() {
        Log.d("this is", "subclass Impl")
    }
}

abstract class superclass(val dummy: Int) {
    abstract fun f2()

    companion object : SingletonHolder<superclass, Int>( { Builder.build(it) } )
}

class superclass_Impl(val par: Int): superclass(par) {
    override fun f2() {
        Log.d("this is", "superclass_Impl")
    }
}

class Builder {
    companion object {
        fun build(par: Int): superclass_Impl {
            return superclass_Impl(par)
        }
    }
}

class test {
    fun test1() {
        superclass.getInstance(1).f2()
        subclass.getInstance(1).f2()  // getInstance is not visible ??
    }
}
</code>```

the SingletonHolder class is derived from the lazy implementation in kotlin and allows passing an argument to the creator function. https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e

superclass is mimicking abstract class MyRoomDatabase : RoomDatabase() on Android, this will create an instance of a sqlite db at runtime and is suggested to be implemented as singleton. This is in my case inside a service. superclass_Impl will be created by the Room Library.

subclass is in my case a subclass of MyRoomDatabase and lives on the client that will connect to the service. I'm trying to extend it to add query methods used only by the client. subclass_Impl will be created by the Room Library.

答:
Clearly you are thinking static members are inherited in java and since companion objects are the same thing, I should be able to the following.

```<code>subclass.getInstance() // as in question, subclass is name of the class not its instance
</code>```

Sorry, this is not allowed. Companion objects are not java's static members. Kotlin is designed to be a language where you don't need such constructs. So don't try to write java code using kotlin features.

if you want to refer a comapnion object member as you refer to java's static members, then you must specify the name of containing class of companion object. In your case

```<code>superclass.getInstance(1).f2()
</code>```

Body:
I'm trying to use the method getInstance from a subclass.

Any idea why the mentioned method is unaccessible and how to change this code so i can access it?

For the curious mind, this example structure comes from trying to subclass a Room database class on Android.

open class SingletonHolder<out T: Any, in A>(creator: (A) -> T) {
    private var creator: ((A) -> T)? = creator
    @Volatile private var instance: T? = null

    fun getInstance(arg: A): T {
        val i = instance
        if (i != null) {
            return i
        }

        return synchronized(this) {
            val i2 = instance
            if (i2 != null) {
                i2
            } else {
                val created = creator!!(arg)
                instance = created
                creator = null
                created
            }
        }
    }
}

abstract class subclass(val par: Int): superclass(par) {
    abstract fun function1()
}

class subclass_Impl(val par1: Int): subclass(par1) {
    override fun function1() {
        Log.d("unused", "unused")
    }

    override fun f2() {
        Log.d("this is", "subclass Impl")
    }
}

abstract class superclass(val dummy: Int) {
    abstract fun f2()

    companion object : SingletonHolder<superclass, Int>( { Builder.build(it) } )
}

class superclass_Impl(val par: Int): superclass(par) {
    override fun f2() {
        Log.d("this is", "superclass_Impl")
    }
}

class Builder {
    companion object {
        fun build(par: Int): superclass_Impl {
            return superclass_Impl(par)
        }
    }
}

class test {
    fun test1() {
        superclass.getInstance(1).f2()
        subclass.getInstance(1).f2()  // getInstance is not visible ??
    }
}

the SingletonHolder class is derived from the lazy implementation in kotlin and allows passing an argument to the creator function. https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e

superclass is mimicking abstract class MyRoomDatabase : RoomDatabase() on Android, this will create an instance of a sqlite db at runtime and is suggested to be implemented as singleton. This is in my case inside a service. superclass_Impl will be created by the Room Library.

subclass is in my case a subclass of MyRoomDatabase and lives on the client that will connect to the service. I'm trying to extend it to add query methods used only by the client. subclass_Impl will be created by the Room Library.

Body:
Clearly you are thinking static members are inherited in java and since companion objects are the same thing, I should be able to the following.

subclass.getInstance() // as in question, subclass is name of the class not its instance

Sorry, this is not allowed. Companion objects are not java's static members. Kotlin is designed to be a language where you don't need such constructs. So don't try to write java code using kotlin features.

if you want to refer a comapnion object member as you refer to java's static members, then you must specify the name of containing class of companion object. In your case

superclass.getInstance(1).f2()


问:
Name of current value in Knockout
I'm getting started with Knockout.  I can't figure out how to setup up the binding in the valuesTemplate.  What is the name of the current value of the iterator?</p>

```<code><div id="knock">
    <p>Name: <input data-bind="value: Name" /></p>
    <table>
        <thead><tr><td>Value</td></tr></thead>
          <tbody data-bind="template: {name: 'valuesTemplate', foreach: Values}" />
    </table>

    <script type="text/html" id="valuesTemplate">
        <tr><td><input data-bind="value: value" /></td></tr>
    </script>
</div>

<script type="text/javascript">
    var data = {"Name":"Fish","Values":["Cod","Salmon","Perch","Glish"],"Id":"lookups/1"};
    var viewModel = ko.mapping.fromJS(data);
    ko.applyBindings(viewModel);
</script>
</code>```

答:
Inside of a jQuery Template, you can access the current context by using $data or $item.data, so like:

```<code><script type="text/html" id="valuesTemplate">
     <tr><td><input data-bind="value: $data" /></td></tr>
</script>
</code>```

However, if you are using observables, you are going to want your values array to contain objects rather than just strings.

ContentLicense: CC BY-SA 3.0

Title: Name of current value in Knockout

Body:
I'm getting started with Knockout.  I can't figure out how to setup up the binding in the valuesTemplate.  What is the name of the current value of the iterator?

Name: <input data-bind="value: Name" />

Value

Body:
Inside of a jQuery Template, you can access the current context by using $data or $item.data, so like:

<script type="text/html" id="valuesTemplate">
     <tr><td><input data-bind="value: $data" /></td></tr>
</script>

However, if you are using observables, you are going to want your values array to contain objects rather than just strings.


问:
How to solve problem with Two Date Fields and multiple cases
I have two tables

```<code>(CREATE TABLE ta_product_discount_details(
  RowID int(10) NOT NULL AUTO_INCREMENT,
  DiscountID int(11) DEFAULT NULL,
  SKU varchar(50) DEFAULT NULL,
  FromDate date DEFAULT NULL,
  ToDate date DEFAULT NULL,
  Price double DEFAULT,
  Timestamp timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (RowID)
)
</code>```

and
anotheer temp table with the same structure that i use as a temp table to insert new rows.

Now, my problem is this:

For example:
In main list i have Product1 with Discount Price that goes active between two dates (FromDate, ToDate). Everything is OK by far.
But, when i create another list with the same product but different dates, i want do "disable" the first product but the problem is when i start checking dates which one is bigger so price from that list is Enabled. It is hard to explain everything because we could have multiple cases:

Example

What if the first list is like this

FromDate: 02/14/2020, ToDate: 06/24/2020.

And then the second list is created like this -

FromDate: 02/16/2020, ToDate: 06/30/2020.....

and much more cases like this one.

Please help if someone knows what shoul i do.
By the way, i am using MySQL 5.6.

答: You can create the trigger which will disable the previous product on insert of new one of same product but for that you might have to add another column to know which one is enabled or disabled.</p>

Body:
I have two tables

(CREATE TABLE ta_product_discount_details(
  RowID int(10) NOT NULL AUTO_INCREMENT,
  DiscountID int(11) DEFAULT NULL,
  SKU varchar(50) DEFAULT NULL,
  FromDate date DEFAULT NULL,
  ToDate date DEFAULT NULL,
  Price double DEFAULT,
  Timestamp timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (RowID)
)

and
anotheer temp table with the same structure that i use as a temp table to insert new rows.

Now, my problem is this:

For example:
In main list i have Product1 with Discount Price that goes active between two dates (FromDate, ToDate). Everything is OK by far.
But, when i create another list with the same product but different dates, i want do "disable" the first product but the problem is when i start checking dates which one is bigger so price from that list is Enabled. It is hard to explain everything because we could have multiple cases:

Example

What if the first list is like this

FromDate: 02/14/2020, ToDate: 06/24/2020.

And then the second list is created like this -

FromDate: 02/16/2020, ToDate: 06/30/2020.....

and much more cases like this one.

Please help if someone knows what shoul i do.
By the way, i am using MySQL 5.6.


问:
Multi file uploader in Shopify Debut theme
I'm customizing my page to upload multiple files (photos). This is the code that I have so far and according to this link it should work:
https://shopify.dev/tutorials/customize-theme-get-customization-information-for-products
in the link go to "Allow file uploads" if you want to check.

```<code>{% form 'product', product, class:form_classes, data-product-form: '', enctype:"multipart/form-data" %}
            {% unless product.has_only_default_variant %}
              <div class="product-form__controls-group">
                {% for option in product.options_with_values %}
                  <div class="selector-wrapper js product-form__item">

                    <select class="single-option-selector single-option-selector-{{ section.id }} product-form__input"
                      id="SingleOptionSelector-{{ forloop.index0 }}"
                      data-index="option{{ forloop.index }}"
                    >
                      {% for value in option.values %}
                        <option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option>
                      {% endfor %}
                    </select>
                  </div>
                {% endfor %}
              </div>
            {% endunless %}

            <select name="id" id="ProductSelect-{{ section.id }}" class="product-form__variants no-js">
              {% for variant in product.variants %}
                <option value="{{ variant.id }}"
                  {%- if variant == current_variant %} selected="selected" {%- endif -%}
                >
                  {{ variant.title }}  {%- if variant.available == false %} - {{ 'products.product.sold_out' | t }}{% endif %}
                </option>
              {% endfor %}
            </select>

            {% if section.settings.show_quantity_selector %}
            {% comment %}
              <div class="product-form__controls-group">
                <div class="product-form__item">
                  <input type="number" id="Quantity-{{ section.id }}"
                    name="quantity" value="1" min="1" pattern="[0-9]*"
                    class="product-form__input product-form__input--quantity" data-quantity-input
                  >
                </div>
              </div>

                <div class="qtydiv">
                {% comment %}<label for="Quantity" class="quantity-selector">Quantity</label>{% endcomment %}
                <div class="qtybox">
                  <span class="btnqty qtyminus icon icon-minus">-</span>
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  <span class="btnqty qtyplus icon icon-plus">+</span>
                </div>
              </div>
        {% endcomment %}
            {% endif %}

            <div class="product-form__error-message-wrapper product-form__error-message-wrapper--hidden{% if section.settings.enable_payment_button %} product-form__error-message-wrapper--has-payment-button{% endif %}"
              data-error-message-wrapper
              role="alert"
            >
              <span class="visually-hidden">{{ 'general.accessibility.error' | t }} </span>
              {% include 'icon-error' %}
              <span class="product-form__error-message" data-error-message>{{ 'products.product.quantity_minimum_message' | t }}</span>
            </div>

            <div class="product-form__controls-group product-form__controls-group--submit">
              <div class="qtydiv">
                {% comment %}<label for="Quantity" class="quantity-selector">Quantity</label>{% endcomment %}
                <div class="qtybox">
                  <span class="btnqty qtyminus icon icon-minus">-</span>
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  <span class="btnqty qtyplus icon icon-plus">+</span>
                </div>
              </div>
              <div class="product-form__item product-form__item--submit
                {%- if section.settings.enable_payment_button %} product-form__item--payment-button {%- endif -%}
                {%- if product.has_only_default_variant %} product-form__item--no-variants {%- endif -%}"
              >
                <button type="submit" name="add"
                  {% unless current_variant.available %} aria-disabled="true"{% endunless %}
                  aria-label="{% unless current_variant.available %}{{ 'products.product.sold_out' | t }}{% else %}{{ 'products.product.add_to_cart' | t }}{% endunless %}"
                  class="btn product-form__cart-submit{% if section.settings.enable_payment_button %} btn--secondary-accent{% endif %}"
                  data-add-to-cart>
                  <span data-add-to-cart-text>
                    {% unless current_variant.available %}
                      {{ 'products.product.sold_out' | t }}
                    {% else %}
                      {{ 'products.product.add_to_cart' | t }}
                    {% endunless %}
                  </span>
                  <span class="hide" data-loader>
                    {% include 'icon-spinner' %}
                  </span>
                </button>
                {% if section.settings.enable_payment_button %}
                  {{ form | payment_button }}
                {% endif %}
              </div>
                    <input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>
              </div>
            </div>
          {% endform %}
</code>```

This is my form that according to the link must have the attribute

```<code>enctype = "multipart / form-data".
</code>```

At the bottom of the form it is in input type = "file".

```<code><input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>
</code>```

And this is the code in the cart-template.liquid.

```<code><div class="list-view-item__title">
                      <a href="{{ item.url }}" class="cart__product-title" data-cart-item-title>
                        {{ item.product.title }}<br>
                        {% assign property_size = item.properties | size %}
                          {% if property_size > 0 %}
                            {% for p in item.properties %}
                                {{ item.properties.count }}
                              {% assign first_character_in_key = p.first | truncate: 1, '' %}
                              {% unless p.last == blank or first_character_in_key == '_' %}
                                {{ p.first }}:
                                {% if p.last contains '/uploads/' %}
                                  <a class="lightbox" href="{{ p.last }}">{{ property_size }}</a>
                                {% else %}
                                  {{ p.last }}
                                {% endif %}
                                <br>
                              {% endunless %}
                            {% endfor %}
                          {% endif %}
                      </a>
                    </div>
</code>```

The problem is the property_size variable gets value one even if I upload two or more images, when in fact I should return the amount of properties that the item has.
Can anyone help me please? What I am doing wrong?

答:
The Debut theme probably has changed since this tutorial was uploaded, and since it is not supported, probably won't be updated.

If you add a type="text" input instead of a type="file" the property gets added as expected. This happens because the _initAddToCart function (assets/theme.js line 6447) gets the form HTML element and pass it along to another function.

```<code>var $data = $(this.selectors.productForm, this.$container);
this._addItemToCart($data);
</code>```

Then in the _addItemToCart function (assets/theme.js line 6513), the form is serialized to a string:

```<code>var params = {
  url: '/cart/add.js',
  data: $(data).serialize(),
  dataType: 'json',
};
$.post(params).done(...
</code>```

This function will ignore the file inputs, as explained in the jQuery documentation:

```<code>Data from file select elements is not serialized.
</code>```

To send the file, the FormData browser API can be used. But to use it with the jQuery AJAX call, some properties must be set:

```<code>var params = {
  url: '/cart/add.js',
  // data: $(data).serialize(),
  dataType: 'json',
  // Disable the jQuery data processing, and send the FormData object
  contentType: false,
  processData: false,
  data: new FormData($(data).get()[0])
};
$.post(params).done(...
</code>```

However, since the HTML file <input> has name="properties[Photo]", only the last of the uploaded files will be added to the cart item's Photo property.
I tried with name="properties[Photo][]", but the cart/add.js call only returns an error 500 with the message "Internal Server Error".

So to upload multiple files you could add some custom code to the _addItemToCart function, to get each File from the <input> and add to the FormData with a different key for each file.

Body:
I'm customizing my page to upload multiple files (photos). This is the code that I have so far and according to this link it should work:
https://shopify.dev/tutorials/customize-theme-get-customization-information-for-products
in the link go to "Allow file uploads" if you want to check.

{% form 'product', product, class:form_classes, data-product-form: '', enctype:"multipart/form-data" %}
            {% unless product.has_only_default_variant %}

                {% for option in product.options_with_values %}

                    <select class="single-option-selector single-option-selector-{{ section.id }} product-form__input"
                      id="SingleOptionSelector-{{ forloop.index0 }}"
                      data-index="option{{ forloop.index }}"
                    >
                      {% for value in option.values %}
                        <option value="{{ value | escape }}"{% if option.selected_value == value %} selected="selected"{% endif %}>{{ value }}</option>
                      {% endfor %}
                    </select>

                {% endfor %}

            {% endunless %}

            <select name="id" id="ProductSelect-{{ section.id }}" class="product-form__variants no-js">
              {% for variant in product.variants %}
                <option value="{{ variant.id }}"
                  {%- if variant == current_variant %} selected="selected" {%- endif -%}
                >
                  {{ variant.title }}  {%- if variant.available == false %} - {{ 'products.product.sold_out' | t }}{% endif %}
                </option>
              {% endfor %}
            </select>

            {% if section.settings.show_quantity_selector %}
            {% comment %}

                  <input type="number" id="Quantity-{{ section.id }}"
                    name="quantity" value="1" min="1" pattern="[0-9]*"
                    class="product-form__input product-form__input--quantity" data-quantity-input
                  >

                {% comment %}Quantity{% endcomment %}

                  -
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  +

        {% endcomment %}
            {% endif %}

              {{ 'general.accessibility.error' | t }}
              {% include 'icon-error' %}
              {{ 'products.product.quantity_minimum_message' | t }}

                {% comment %}Quantity{% endcomment %}

                  -
                  <input type="text" id="quantity" name="quantity" value="1" min="1" class="quantity-selector quantity-input" readonly="">
                  +

                <button type="submit" name="add"
                  {% unless current_variant.available %} aria-disabled="true"{% endunless %}
                  aria-label="{% unless current_variant.available %}{{ 'products.product.sold_out' | t }}{% else %}{{ 'products.product.add_to_cart' | t }}{% endunless %}"
                  class="btn product-form__cart-submit{% if section.settings.enable_payment_button %} btn--secondary-accent{% endif %}"
                  data-add-to-cart>

                    {% unless current_variant.available %}
                      {{ 'products.product.sold_out' | t }}
                    {% else %}
                      {{ 'products.product.add_to_cart' | t }}
                    {% endunless %}

                    {% include 'icon-spinner' %}

                </button>
                {% if section.settings.enable_payment_button %}
                  {{ form | payment_button }}
                {% endif %}

                    <input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>

          {% endform %}

This is my form that according to the link must have the attribute

enctype = "multipart / form-data".

At the bottom of the form it is in input type = "file".

<input required class="required product-form__input" id="photo" type="file" name="properties[Photo]" multiple>

And this is the code in the cart-template.liquid.

                        {{ item.product.title }}

                        {% assign property_size = item.properties | size %}
                          {% if property_size > 0 %}
                            {% for p in item.properties %}
                                {{ item.properties.count }}
                              {% assign first_character_in_key = p.first | truncate: 1, '' %}
                              {% unless p.last == blank or first_character_in_key == '_' %}
                                {{ p.first }}:
                                {% if p.last contains '/uploads/' %}
                                  {{ property_size }}
                                {% else %}
                                  {{ p.last }}
                                {% endif %}

                              {% endunless %}
                            {% endfor %}
                          {% endif %}

The problem is the property_size variable gets value one even if I upload two or more images, when in fact I should return the amount of properties that the item has.
Can anyone help me please? What I am doing wrong?

Body:
The Debut theme probably has changed since this tutorial was uploaded, and since it is not supported, probably won't be updated.

If you add a type="text" input instead of a type="file" the property gets added as expected. This happens because the _initAddToCart function (assets/theme.js line 6447) gets the form HTML element and pass it along to another function.

var $data = $(this.selectors.productForm, this.$container);
this._addItemToCart($data);

Then in the _addItemToCart function (assets/theme.js line 6513), the form is serialized to a string:

var params = {
  url: '/cart/add.js',
  data: $(data).serialize(),
  dataType: 'json',
};
$.post(params).done(...

This function will ignore the file inputs, as explained in the jQuery documentation:

Data from file select elements is not serialized.

To send the file, the FormData browser API can be used. But to use it with the jQuery AJAX call, some properties must be set:

var params = {
  url: '/cart/add.js',
  // data: $(data).serialize(),
  dataType: 'json',
  // Disable the jQuery data processing, and send the FormData object
  contentType: false,
  processData: false,
  data: new FormData($(data).get()[0])
};
$.post(params).done(...

However, since the HTML file <input> has name="properties[Photo]", only the last of the uploaded files will be added to the cart item's Photo property.
I tried with name="properties[Photo][]", but the cart/add.js call only returns an error 500 with the message "Internal Server Error".

So to upload multiple files you could add some custom code to the _addItemToCart function, to get each File from the <input> and add to the FormData with a different key for each file.


问:
Is it guaranteed that the function passed to useEffect will be called at least once after the component is called, even in concurrent mode?
Except if exceptions occur of course.

I couldn't find a clear answer to this.

In their reference useSubscription hook implementation they say:

It is important not to subscribe while rendering because this can lead to memory leaks.

But it's not clear if it's possible to implement subscriptions in the body that can't lead to a memory leaks, or if subscribing in the body will, eventually, cause memory leaks if the unsubscription happens inside useEffect.

I'm especially interested in knowing if this holds true under concurrent mode.

答:
Is it guaranteed that the function passed to useEffect will be called at least once after the component is called, even in concurrent mode?

I think that is not guaranteed.

Suppose we start in a situation where your component is not mounted. Rendering begins, and your component is among those that needs to be rendered, so it gets called. But then before it can be committed, a higher priority update comes in, which restarts rendering for a portion of the component tree. In this new render, the parent of your component decides that your component is no longer needed. This render finishes and gets committed, with your component not among the outputs.

It wasn't there before this all started, and it wasn't there after the commit, so its effects do not run. But it did get called during the process, so any side effects in the body of your component happened. You're now subscribed to an event, with no way to unsubscribe from it.


问:
How to assign the same Id to Anagram of character?
I want to assign the same Id to Anagram chain of character with Javascript.

like :

Paul Leblanc

and

Leblanc Paul

(sorry for my english )

Thank you by advance

答:
If you want to assign a unique id based on a string with the same result for anagram, you need to sort the letters of you string and make the id based on this.

To get your seed from a string :

```<code>function getSeed(str) { return str.split('').sort().join('') }
</code>```

you can then generate an id with this seed, by making a md5 for example.

Body:
If you want to assign a unique id based on a string with the same result for anagram, you need to sort the letters of you string and make the id based on this.

To get your seed from a string :

function getSeed(str) { return str.split('').sort().join('') }

you can then generate an id with this seed, by making a md5 for example.


问:
Excel VBA, 2003 - Convert string to 2-dimensional array
I inherited an old Excel (.xls) spreadsheet starting from 2005.

For some reason the spreadsheet uses the name manager for quite large data stored as strings instead of referring to a table with the data. This is what I am trying to change so it will be easier to change the data currently stored in the name manager (at the moment it is not possible to change any of the data as the character limit in the name manager has somehow been exceeded).

I would like to make use of as much of the current VBA code as possible which is why I currently have a setup where I use VBA to convert data from the spreadsheet to a string in the form of

```<code>"CELL"\"CELL"\"...""CELL";"CELL"\"CELL"\"CELL";
</code>```

Where I (or the old code) make use of backslash, \, as a delimiter for a new column and semicolon, ;, as a delimiter for a new row.

I want to convert my string to an 2-dimensional array called 'arkArray' so I can make use of the following code:

```<code>arkCellData = arkArray(i, j)
</code>```

What is the best way to do so?

答:
How to make a two dimensional array.</p>

```<code>Sub test()
    Dim myArray(), vS, vS2
    Dim vMax()
    Dim s As String
    Dim myMax As Integer, i As Integer,  j As Integer
    Dim r As Long

    s = "apple\banana\John;some\reason\use\Tom;table\data\limit;"

    If Right(s, 1) = ";" Then
        s = Left(s, Len(s) - 1)
    End If

    vS = Split(s, ";")
    ReDim vMax(UBound(vS))

    For i = 0 To UBound(vS)
        vS2 = Split(vS(i), "\")
        vMax(i) = UBound(vS2) + 1
    Next i

    myMax = WorksheetFunction.Max(vMax)
    r = UBound(vS) + 1

    ReDim myArray(1 To r, 1 To myMax)

    For i = 1 To UBound(myArray)
        vS2 = Split(vS(i - 1), "\")
        For j = 1 To UBound(vS2) + 1
            myArray(i, j) = vS2(j - 1)
        Next j
    Next i
    Range("a1").Resize(r, myMax) = myArray

End Sub
</code>```

Body:
I inherited an old Excel (.xls) spreadsheet starting from 2005.

For some reason the spreadsheet uses the name manager for quite large data stored as strings instead of referring to a table with the data. This is what I am trying to change so it will be easier to change the data currently stored in the name manager (at the moment it is not possible to change any of the data as the character limit in the name manager has somehow been exceeded).

I would like to make use of as much of the current VBA code as possible which is why I currently have a setup where I use VBA to convert data from the spreadsheet to a string in the form of

"CELL"\"CELL"\"...""CELL";"CELL"\"CELL"\"CELL";

Where I (or the old code) make use of backslash, \, as a delimiter for a new column and semicolon, ;, as a delimiter for a new row.

I want to convert my string to an 2-dimensional array called 'arkArray' so I can make use of the following code:

arkCellData = arkArray(i, j)

What is the best way to do so?

Body:
How to make a two dimensional array.

Sub test()
    Dim myArray(), vS, vS2
    Dim vMax()
    Dim s As String
    Dim myMax As Integer, i As Integer,  j As Integer
    Dim r As Long

    s = "apple\banana\John;some\reason\use\Tom;table\data\limit;"

    If Right(s, 1) = ";" Then
        s = Left(s, Len(s) - 1)
    End If

    vS = Split(s, ";")
    ReDim vMax(UBound(vS))

    For i = 0 To UBound(vS)
        vS2 = Split(vS(i), "\")
        vMax(i) = UBound(vS2) + 1
    Next i

    myMax = WorksheetFunction.Max(vMax)
    r = UBound(vS) + 1

    ReDim myArray(1 To r, 1 To myMax)

    For i = 1 To UBound(myArray)
        vS2 = Split(vS(i - 1), "\")
        For j = 1 To UBound(vS2) + 1
            myArray(i, j) = vS2(j - 1)
        Next j
    Next i
    Range("a1").Resize(r, myMax) = myArray

End Sub


问:
Using sed to replace <? with <?php
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

```<code>$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php
</code>```

答:
Do you really have to use sed, or can you use perl as well?

```<code>perl -pi.tmp -e 's,^<\?(?!php),<?php,' *.php *.inc
rm *.tmp
</code>```

I am using a negative look-ahead to avoid generating <?phpphp in cases where the files already start with the correct characters.

Title: Using sed to replace <? with <?php

Body:
I'm trying to programmatically replace <? with <?php in a bunch of file, but my sed regex isn't behaving like I expected. Can you tell me what's wrong with it?

I'm testing it on the command line here:

$ sed -e 's/<\?/<\?php/g'
<?
<?php?<?php
d
<?phpd<?php

Body:
Do you really have to use sed, or can you use perl as well?

perl -pi.tmp -e 's,^<\?(?!php),<?php,' *.php *.inc
rm *.tmp

I am using a negative look-ahead to avoid generating <?phpphp in cases where the files already start with the correct characters.


问:
Unique Ways To Give Change- Not Outputting Expected Values
I'm trying to create a program that outputs all the possible unique ways to make change for a given input using ONLY recursion and constant memory(so no loops).

For an amount of 25 cents it should print out all possible combinations in the following example format:

```<code>0*25+0*10+1*5+20*1
0*25+0*10+2*5+15*1
etc..
</code>```

Where 0* is the number of quarters(25) used as an example

The problem with my program is that it only prints out:

```<code>0=0*25+0*10+0*5+25*1+
</code>```

and not the rest of the combinations. I suspect this is due to me messing up the printCombinations and getLargerCombinations methods (which are basically recursive methods that simulate a for loop), but I can't figure out what the problem is.

Here is the whole code:

```<code>public class HW {

    static int[] coins = {25,10,5,1};
    static int[] counts = new int[coins.length];

    static void getCombinations(int[] counts, int startIndex, int totalAmount) {
        if(startIndex>= coins.length) {
            System.out.print(""+totalAmount+"=");
            printCombinations(0);
            return;
        }

        if(startIndex == coins.length - 1) {

            if(totalAmount%coins[startIndex]==0) //good combo
            {
                //setting count of coins at start index
                counts[startIndex] = totalAmount/coins[startIndex];
                //move on to recursive calls
                getCombinations(counts, startIndex + 1, 0);
            }
        }

        else //still need to choose 0-N larger coins
        {
            getLargerCoins(0, totalAmount, startIndex);

        }

    }

    //Prints out all the possible combinations of change
    static void printCombinations(int i) {
        if(i >= coins.length) {
            System.out.print("\n");
            return;
        }
        System.out.print("" + counts[i] + "*" + coins[i] + "+");
        printCombinations(++i);
    }

    static void getLargerCoins(int j, int totalAmount, int startIndex) {
        if(j >= totalAmount/coins[startIndex]) {
            return;
        }
        //for every cycle in the loop, we choose an arbitray # of larger coins and proceed next
        counts[startIndex] = j;
        getCombinations(counts, startIndex+1, totalAmount-coins[startIndex]*j);
        j++;
    }

    public static void main(String[] args) {
        getCombinations(counts, 0, 25);
    }

}
</code>```

****EDIT:*****

Under the getLargerCoins method I just iterated j++ but forgot to call the getLargerCoins method to continue the recursion. Fixed the line by writing:

```<code>getLargerCoins(++j, totalAmount, startIndex);
</code>```

Output when running the program:

```<code>0=0*25+0*10+0*5+25*1+
0=0*25+0*10+1*5+20*1+
0=0*25+0*10+2*5+15*1+
0=0*25+0*10+3*5+10*1+
0=0*25+0*10+4*5+5*1+
0=0*25+1*10+0*5+15*1+
0=0*25+1*10+1*5+10*1+
0=0*25+1*10+2*5+5*1+
</code>```

However, it is still not outputting all the possible combinations

答:
Everything you can solve with a loop you can solve with recursion too (not very readable, but working solution):

```<code>public static void printCombinations(int[] coins, int amount) {
    printCombinations(coins, new int[coins.length], amount, 0);
}

private static void printCombinations(int[] coins, int[] counts, int amount, int index) {
    if (amount == 0) {
        print(coins, counts, 0, "");
    } else if (amount > 0) {
        printCombinationsLoop(coins, counts, amount, index);
    }
}

private static void printCombinationsLoop(int[] coins, int[] counts, int amount, int index) {
    counts[index]++;
    printCombinations(coins, counts, amount - coins[index], index);
    counts[index]--;
    if (index + 1 < coins.length)
        printCombinationsLoop(coins, counts, amount, index + 1);
}

private static void print(int[] coins, int[] counts, int index, String s) {
    if (counts[index] > 0) {
        if (!s.isEmpty())
            s += "+";
        s += counts[index] + "*" + coins[index];
    }
    if (index + 1 == coins.length)
        System.out.println(s);
    else
        print(coins, counts, index + 1, s);
}
</code>```

The coins should be unique for this to work properly.

Body:
I'm trying to create a program that outputs all the possible unique ways to make change for a given input using ONLY recursion and constant memory(so no loops).

For an amount of 25 cents it should print out all possible combinations in the following example format:

0*25+0*10+1*5+20*1
0*25+0*10+2*5+15*1
etc..

Where 0* is the number of quarters(25) used as an example

The problem with my program is that it only prints out:

0=0*25+0*10+0*5+25*1+

and not the rest of the combinations. I suspect this is due to me messing up the printCombinations and getLargerCombinations methods (which are basically recursive methods that simulate a for loop), but I can't figure out what the problem is.

Here is the whole code:

public class HW {

    static int[] coins = {25,10,5,1};
    static int[] counts = new int[coins.length];

    static void getCombinations(int[] counts, int startIndex, int totalAmount) {
        if(startIndex>= coins.length) {
            System.out.print(""+totalAmount+"=");
            printCombinations(0);
            return;
        }

        if(startIndex == coins.length - 1) {

            if(totalAmount%coins[startIndex]==0) //good combo
            {
                //setting count of coins at start index
                counts[startIndex] = totalAmount/coins[startIndex];
                //move on to recursive calls
                getCombinations(counts, startIndex + 1, 0);
            }
        }

        else //still need to choose 0-N larger coins
        {
            getLargerCoins(0, totalAmount, startIndex);

        }

    }

    //Prints out all the possible combinations of change
    static void printCombinations(int i) {
        if(i >= coins.length) {
            System.out.print("\n");
            return;
        }
        System.out.print("" + counts[i] + "*" + coins[i] + "+");
        printCombinations(++i);
    }

    static void getLargerCoins(int j, int totalAmount, int startIndex) {
        if(j >= totalAmount/coins[startIndex]) {
            return;
        }
        //for every cycle in the loop, we choose an arbitray # of larger coins and proceed next
        counts[startIndex] = j;
        getCombinations(counts, startIndex+1, totalAmount-coins[startIndex]*j);
        j++;
    }

    public static void main(String[] args) {
        getCombinations(counts, 0, 25);
    }

}

****EDIT:*****

Under the getLargerCoins method I just iterated j++ but forgot to call the getLargerCoins method to continue the recursion. Fixed the line by writing:

getLargerCoins(++j, totalAmount, startIndex);

Output when running the program:

0=0*25+0*10+0*5+25*1+
0=0*25+0*10+1*5+20*1+
0=0*25+0*10+2*5+15*1+
0=0*25+0*10+3*5+10*1+
0=0*25+0*10+4*5+5*1+
0=0*25+1*10+0*5+15*1+
0=0*25+1*10+1*5+10*1+
0=0*25+1*10+2*5+5*1+

However, it is still not outputting all the possible combinations

Body:
Everything you can solve with a loop you can solve with recursion too (not very readable, but working solution):

public static void printCombinations(int[] coins, int amount) {
    printCombinations(coins, new int[coins.length], amount, 0);
}

private static void printCombinations(int[] coins, int[] counts, int amount, int index) {
    if (amount == 0) {
        print(coins, counts, 0, "");
    } else if (amount > 0) {
        printCombinationsLoop(coins, counts, amount, index);
    }
}

private static void printCombinationsLoop(int[] coins, int[] counts, int amount, int index) {
    counts[index]++;
    printCombinations(coins, counts, amount - coins[index], index);
    counts[index]--;
    if (index + 1 < coins.length)
        printCombinationsLoop(coins, counts, amount, index + 1);
}

private static void print(int[] coins, int[] counts, int index, String s) {
    if (counts[index] > 0) {
        if (!s.isEmpty())
            s += "+";
        s += counts[index] + "*" + coins[index];
    }
    if (index + 1 == coins.length)
        System.out.println(s);
    else
        print(coins, counts, index + 1, s);
}

The coins should be unique for this to work properly.


问:
Open file with specific cursor location
I'm trying to write a program that can search a word in a .txt file and open that file with the cursor at the specific location where the word was found (In front of the word). I've already implemented the searching and I know how to open a file, but I can't seem to find a way to open the file with the cursor at a specific position. Is there a way to do such a thing? Thanks :)

Edit : Just to clarify, when I say 'Open', I mean literally opening the file with Notepad, not opening the file with a Streamreader.

Edit 2 : I can't assume Notepad is the default text editor, but if needs be, I can force the file to be opened with it.

答:
You can't do this with notepad, but you could do it with notepad++ using the following command line arguments</p>

```<code>-n: Scroll to indicated line (LineNumber) on filepath.
-c: Scroll to indicated column (ColumnNumber) on filepath.
-p: Scroll to indicated 0 base position (Position) on filepath.
</code>```

Title: Open file with specific cursor location

Body:
You can't do this with notepad, but you could do it with notepad++ using the following command line arguments

-n: Scroll to indicated line (LineNumber) on filepath.
-c: Scroll to indicated column (ColumnNumber) on filepath.
-p: Scroll to indicated 0 base position (Position) on filepath.


问:
Clicking on a button with changing xpath
I just started working with Selenium webdriver to try automate clicking a button in a discord chat based on preconditions. The problem I am having is being able to classify this button.

For starters, the HTML code is as follows:

```<code><div tabindex="0" class="reactionInner-15NvIl" aria-label="♥, press to react" aria-pressed="false" role="button"><img src="/assets/1afd3c799f3e158662a70498e83e2a87.svg" alt="♥" draggable="false" class="emoji"><div class="reactionCount-2mvXRV" style="min-width: 9px;">1</div></div>
</code>```

What I first tried to do was to find_element_by_xpath:

```<code>driver.find_element_by_xpath('/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[48]/div[1]/div[2]/div[2]/div[1]/div/div').click()
</code>```

But, when a new opportunity for this reaction comes up, the xpath changes:

```<code>/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[50]/div[1]/div[2]/div[2]/div[1]/div/div
</code>```

Notice the only part changing it the div[48] to div[50]

The next thing I tried was to find_element_by_class_name:

```<code>element = driver.find_element_by_class_name('reactionInner-15NvIl')
driver.execute_script("arguments[0].click();", element)
</code>```

The reason I did this was because I was having a problem with simply doing:

```<code>driver.find_element_by_class_name('reactionInner-15NvIl').click()
</code>```

That code would give me an error saying Message: element click intercepted: Element
...
 is not clickable at point (405, 94). Other element would receive the click: ... and the code wouldn't run. The program runs with the execute_script but it just isn't doing anything, the button is not being clicked. So if anyone has any idea how to be able to click this button, any help would be appreciated!

答:
Induce WebDriverWait and wait for element_to_be_clickable() and following css selector.

```<code>WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[class*='reactionInner-'][role='button']"))).click()
</code>```

You need to import following libraries.

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
</code>```

Update:

Induce Javascript Executor to click.

```<code>driver.execute_script("arguments[0].click();", WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[class*='reactionInner-'][role='button']"))))
</code>```

Body:
I just started working with Selenium webdriver to try automate clicking a button in a discord chat based on preconditions. The problem I am having is being able to classify this button.

For starters, the HTML code is as follows:

1

What I first tried to do was to find_element_by_xpath:

driver.find_element_by_xpath('/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[48]/div[1]/div[2]/div[2]/div[1]/div/div').click()

But, when a new opportunity for this reaction comes up, the xpath changes:

/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[50]/div[1]/div[2]/div[2]/div[1]/div/div

Notice the only part changing it the div[48] to div[50]

The next thing I tried was to find_element_by_class_name:

element = driver.find_element_by_class_name('reactionInner-15NvIl')
driver.execute_script("arguments[0].click();", element)

The reason I did this was because I was having a problem with simply doing:

driver.find_element_by_class_name('reactionInner-15NvIl').click()

That code would give me an error saying Message: element click intercepted: Element
...
 is not clickable at point (405, 94). Other element would receive the click: ... and the code wouldn't run. The program runs with the execute_script but it just isn't doing anything, the button is not being clicked. So if anyone has any idea how to be able to click this button, any help would be appreciated!

Body:
Induce WebDriverWait and wait for element_to_be_clickable() and following css selector.

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[class*='reactionInner-'][role='button']"))).click()

You need to import following libraries.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

Update:

Induce Javascript Executor to click.

driver.execute_script("arguments[0].click();", WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"div[class*='reactionInner-'][role='button']"))))


问:
two slider values on same page
I'm trying to put two different sliders on the same page. If I just do the below for one slider, it works:

```<code><h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
</script>
</code>```

But if I try to do add a second slider with the coding below, the value display on the second does not work:

```<code><h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<h3><i>New</i> Strength of Belief in Negative Cognition</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief2_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">
</div>
</div>

<script>
var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}
</script>
</code>```

Here is the CSS if it matters:

```<code>.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #fff;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}
</code>```

Any ideas what I'm doing wrong? I am new to javascript, so my error is probably pretty embarrassing.

答:
You have a mistake here output.innerHTML = slider.value; . You should target to output2 as you created it for second slider.

And your .slider_left class on your CSS you set color: #fff that's why this is another reason text will be white color as same as background and won't be visible

Here you can see below how it should be

var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output2.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}</code>```

<!DOCTYPE html>

Strength of Belief

    %

    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">

New Strength of Belief in Negative Cognition

    %

    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">

```

Title: two slider values on same page

Body:
I'm trying to put two different sliders on the same page. If I just do the below for one slider, it works:

Strength of Belief

    %

    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">

But if I try to do add a second slider with the coding below, the value display on the second does not work:

Strength of Belief

    %

    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">

New Strength of Belief in Negative Cognition

    %

    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">

Here is the CSS if it matters:

.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
    color: #fff;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}

Any ideas what I'm doing wrong? I am new to javascript, so my error is probably pretty embarrassing.

Body:
You have a mistake here output.innerHTML = slider.value; . You should target to output2 as you created it for second slider.

And your .slider_left class on your CSS you set color: #fff that's why this is another reason text will be white color as same as background and won't be visible

Here you can see below how it should be

var slider = document.getElementById("oldbelief");
var output = document.getElementById("belief_value");
output.innerHTML = slider.value;

slider.oninput = function() {
  output.innerHTML = this.value;
}
var slider2 = document.getElementById("newbelief");
var output2 = document.getElementById("belief2_value");
output2.innerHTML = slider.value;

slider2.oninput = function() {
  output2.innerHTML = this.value;
}

.slider_left {
    display: inline-block;
    width: 10%;
    text-align: center;
    font-weight: normal;
    font-size: 30px;
}

.slider_mid {
    display: inline-block;
    width: 79%;
}
.slidecontainer {
  width: 100%;
}

.slider, .slider2 {
  -webkit-appearance: none;
  width: 100%;
  height: 10px;
  border-radius: 5px;
  background: #999;
  outline: none;
  opacity: 1;
  -webkit-transition: .2s;
  transition: opacity .2s;
}

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<h3>Strength of Belief</h3>
<div class="slidecontainer">
<div class="slider_left">
    <span id="belief_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider" id="oldbelief">
</div>
</div>

<h3><i>New</i> Strength of Belief in Negative Cognition</h3>
<div class="slidecontainer">
<div class="slider_right">
    <span id="belief2_value"></span>%
</div>
<div class="slider_mid">
    <input type="range" min="1" max="100" value="50" class="slider2" id="newbelief">
</div>
</div>

</body>
</html>


问:
Django PasswordResetView - Where to find the code that actually sends the email?
So, I am looking at the Django PasswordResetView because I am trying to debug an issue with some emails not arriving.

https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.PasswordResetView

All I see in the view is this:

```<code>class PasswordResetView(PasswordContextMixin, FormView):
    email_template_name = 'registration/password_reset_email.html'
    extra_email_context = None
    form_class = PasswordResetForm
    from_email = None
    html_email_template_name = None
    subject_template_name = 'registration/password_reset_subject.txt'
    success_url = reverse_lazy('password_reset_done')
    template_name = 'registration/password_reset_form.html'
    title = _('Password reset')
    token_generator = default_token_generator

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        opts = {
            'use_https': self.request.is_secure(),
            'token_generator': self.token_generator,
            'from_email': self.from_email,
            'email_template_name': self.email_template_name,
            'subject_template_name': self.subject_template_name,
            'request': self.request,
            'html_email_template_name': self.html_email_template_name,
            'extra_email_context': self.extra_email_context,
        }
        form.save(**opts)
        return super().form_valid(form)
</code>```

Where is the actual code that sends the email?

答:
You can find it in the code you quoted:

```<code>class PasswordResetView(PasswordContextMixin, FormView):
    ...

    form_class = PasswordResetForm
    ...

    def form_valid(self, form):
        ...

        form.save(**opts)
        ...
</code>```

Refers to the following:

```<code>class PasswordResetForm(forms.Form):

    ...

    def save(self, domain_override=None,
             subject_template_name='registration/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generate a one-use only link for resetting password and send it to the
        user.
        """
        email = self.cleaned_data["email"]
        if not domain_override:
            current_site = get_current_site(request)
            site_name = current_site.name
            domain = current_site.domain
        else:
            site_name = domain = domain_override
        email_field_name = UserModel.get_email_field_name()
        for user in self.get_users(email):
            user_email = getattr(user, email_field_name)
            context = {
                'email': user_email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
                **(extra_email_context or {}),
            }
            -> self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                user_email, html_email_template_name=html_email_template_name,
            )

    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()
</code>```

Body:
So, I am looking at the Django PasswordResetView because I am trying to debug an issue with some emails not arriving.

https://docs.djangoproject.com/en/3.0/topics/auth/default/#django.contrib.auth.views.PasswordResetView

All I see in the view is this:

class PasswordResetView(PasswordContextMixin, FormView):
    email_template_name = 'registration/password_reset_email.html'
    extra_email_context = None
    form_class = PasswordResetForm
    from_email = None
    html_email_template_name = None
    subject_template_name = 'registration/password_reset_subject.txt'
    success_url = reverse_lazy('password_reset_done')
    template_name = 'registration/password_reset_form.html'
    title = _('Password reset')
    token_generator = default_token_generator

    @method_decorator(csrf_protect)
    def dispatch(self, *args, **kwargs):
        return super().dispatch(*args, **kwargs)

    def form_valid(self, form):
        opts = {
            'use_https': self.request.is_secure(),
            'token_generator': self.token_generator,
            'from_email': self.from_email,
            'email_template_name': self.email_template_name,
            'subject_template_name': self.subject_template_name,
            'request': self.request,
            'html_email_template_name': self.html_email_template_name,
            'extra_email_context': self.extra_email_context,
        }
        form.save(**opts)
        return super().form_valid(form)

Where is the actual code that sends the email?

Body:
You can find it in the code you quoted:

class PasswordResetView(PasswordContextMixin, FormView):
    ...

    form_class = PasswordResetForm
    ...

    def form_valid(self, form):
        ...

        form.save(**opts)
        ...

Refers to the following:

class PasswordResetForm(forms.Form):

    ...

    def save(self, domain_override=None,
             subject_template_name='registration/password_reset_subject.txt',
             email_template_name='registration/password_reset_email.html',
             use_https=False, token_generator=default_token_generator,
             from_email=None, request=None, html_email_template_name=None,
             extra_email_context=None):
        """
        Generate a one-use only link for resetting password and send it to the
        user.
        """
        email = self.cleaned_data["email"]
        if not domain_override:
            current_site = get_current_site(request)
            site_name = current_site.name
            domain = current_site.domain
        else:
            site_name = domain = domain_override
        email_field_name = UserModel.get_email_field_name()
        for user in self.get_users(email):
            user_email = getattr(user, email_field_name)
            context = {
                'email': user_email,
                'domain': domain,
                'site_name': site_name,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'user': user,
                'token': token_generator.make_token(user),
                'protocol': 'https' if use_https else 'http',
                **(extra_email_context or {}),
            }
            -> self.send_mail(
                subject_template_name, email_template_name, context, from_email,
                user_email, html_email_template_name=html_email_template_name,
            )

    def send_mail(self, subject_template_name, email_template_name,
                  context, from_email, to_email, html_email_template_name=None):
        """
        Send a django.core.mail.EmailMultiAlternatives to `to_email`.
        """
        subject = loader.render_to_string(subject_template_name, context)
        # Email subject *must not* contain newlines
        subject = ''.join(subject.splitlines())
        body = loader.render_to_string(email_template_name, context)

        email_message = EmailMultiAlternatives(subject, body, from_email, [to_email])
        if html_email_template_name is not None:
            html_email = loader.render_to_string(html_email_template_name, context)
            email_message.attach_alternative(html_email, 'text/html')

        email_message.send()


问:
Simple way to play a sound file (.aif)
I'm making an app for Mac OS X using Xcode, and I want it to play a alert sound when something happens.

What is the simplest code for playing a sound in Objective-C/Cocoa? Note that my sound file is an .aif.

Also, where do I put the sound file inside my project?

Thank you.

答:
Basic playback of sound is quite easy.

You can use the NSSound class to load the file in a few different ways, for example, by name:

```<code>NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];
</code>```

This will need to be retained if you want to keep it around.

in this case the class will search certain particular directories, including your application bundle, for a sound file with that name. One important note is that the file must have the .aiff (with two f's) extension in order to be found by this method.*

You would probably store the sound file in the Resources folder of your project; that's where "media" files are commonly kept.

Then you can play it very simply, perhaps using a button press:

```<code>- (IBAction)playTheSound:(id)sender {
    NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];
    [myAwesomeSound play];
}
</code>```

It's also possible to do some basic transport control: pausing, stopping, checking whether the sound has finished, and so on.  Please see the Sound Programming Topics Guide for details.

*It's possible to use other formats, too, of course.

Title: Simple way to play a sound file (.aif)

Body:
Basic playback of sound is quite easy.

You can use the NSSound class to load the file in a few different ways, for example, by name:

NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];

This will need to be retained if you want to keep it around.

in this case the class will search certain particular directories, including your application bundle, for a sound file with that name. One important note is that the file must have the .aiff (with two f's) extension in order to be found by this method.*

You would probably store the sound file in the Resources folder of your project; that's where "media" files are commonly kept.

Then you can play it very simply, perhaps using a button press:

- (IBAction)playTheSound:(id)sender {
    NSSound * myAwesomeSound = [NSSound soundNamed:@"AwesomeSound"];
    [myAwesomeSound play];
}

It's also possible to do some basic transport control: pausing, stopping, checking whether the sound has finished, and so on.  Please see the Sound Programming Topics Guide for details.

*It's possible to use other formats, too, of course.