问:
Looping through a numpy array
I have a 5 by 10 array and I want to flip a bit if a random number is greater than 0.9. However, this only works for the first row of the array and it doesn't get to the second and subsequent row. I replaced the bits with 3 and 4 so i can easily see if the flipping occurs. I have been getting results that look like this. </p>

```<code>[[3 1 1 1 4 1 3 1 0 1]
 [1 1 0 0 1 0 1 1 1 0]
 [1 0 1 0 1 0 1 1 1 1]
 [0 0 1 0 1 1 0 1 1 1]
 [0 1 1 0 0 0 0 1 1 1]]

</code>```

<p>Please help me figure out where I'm wrong. </p>

```<code>
from random import random
RM =  np.random.randint(0,2, size=(5,10))
print(RM)
for k in range(0, RM.shape[0]):
    for j in range(0, RM.shape[1]):
        A  = random()
        if A > 0.9:
            if RM[k,j] == 0:
                np.put(RM, [k,j], [3])
                print("k1",k)
                print("j1", j)
            else:
                np.put(RM, [k,j], [4])
                print("k2", k)
        else:
            continue

print(RM)
</code>```

答:
To iterate over a Numpy array, a convenient (and recommended) tool is nditer.

If you want to change values of the iterated array, op_flags=['readwrite']
should be passed.

To have access to the indices of the current element, in case of a
multi-dimension array, flags=['multi_index'] should be passed.

Below you have example code, which also prints indices in each case the current
element has been flipped.

To check how it operates, I added a printout of RM, both before
and after the loop.

```<code>np.random.seed(0)
RM = np.random.randint(0, 2, size=(5, 10))
print('Before:')
print(RM, '\n')
with np.nditer(RM, op_flags=['readwrite'], flags=['multi_index']) as it:
    for x in it:
        A  = np.random.random()
        if A > 0.9:
            x[...] = 1 - x  # Flip
            print(f'Flip: <{it.multi_index}>,  {A:.3f}')
print('\nAfter:')
print(RM)
</code>```

To get repeatable result, I added np.random.seed(0) (remove it in the
target version).

With the above seeding, I got the following result:

```<code>Before:
[[0 1 1 0 1 1 1 1 1 1]
 [1 0 0 1 0 0 0 0 0 1]
 [0 1 1 0 0 1 1 1 1 0]
 [1 0 1 0 1 1 0 1 1 0]
 [0 1 0 1 1 1 1 1 0 1]]

Flip: <(0, 2)>,  0.945
Flip: <(1, 3)>,  0.944
Flip: <(2, 7)>,  0.988
Flip: <(4, 5)>,  0.976
Flip: <(4, 7)>,  0.977

After:
[[0 1 0 0 1 1 1 1 1 1]
 [1 0 0 0 0 0 0 0 0 1]
 [0 1 1 0 0 1 1 0 1 0]
 [1 0 1 0 1 1 0 1 1 0]
 [0 1 0 1 1 0 1 0 0 1]]
</code>```

Compare elements indicated as flipped, in "Before" and "After" sections,
to confirm that the above code does its job.
Check also that no other element has been changed.

A bit tricky element in the above code is x[...] = 1 - x.
Note that 1 - x part reads the current value (so far it is OK).
But if you attempted to save anything to x, writing x =,
then you would break the link to the source array element.
In this case x would point to the new value, but not to the
current array element.

So in order not to break this link, just x[...] = notation is needed.

Title: Looping through a numpy array

Body:
I have a 5 by 10 array and I want to flip a bit if a random number is greater than 0.9. However, this only works for the first row of the array and it doesn't get to the second and subsequent row. I replaced the bits with 3 and 4 so i can easily see if the flipping occurs. I have been getting results that look like this.

[[3 1 1 1 4 1 3 1 0 1]
 [1 1 0 0 1 0 1 1 1 0]
 [1 0 1 0 1 0 1 1 1 1]
 [0 0 1 0 1 1 0 1 1 1]
 [0 1 1 0 0 0 0 1 1 1]]

Please help me figure out where I'm wrong.

from random import random
RM =  np.random.randint(0,2, size=(5,10))
print(RM)
for k in range(0, RM.shape[0]):
    for j in range(0, RM.shape[1]):
        A  = random()
        if A > 0.9:
            if RM[k,j] == 0:
                np.put(RM, [k,j], [3])
                print("k1",k)
                print("j1", j)
            else:
                np.put(RM, [k,j], [4])
                print("k2", k)
        else:
            continue

print(RM)

Body:
To iterate over a Numpy array, a convenient (and recommended) tool is nditer.

If you want to change values of the iterated array, op_flags=['readwrite']
should be passed.

To have access to the indices of the current element, in case of a
multi-dimension array, flags=['multi_index'] should be passed.

Below you have example code, which also prints indices in each case the current
element has been flipped.

To check how it operates, I added a printout of RM, both before
and after the loop.

np.random.seed(0)
RM = np.random.randint(0, 2, size=(5, 10))
print('Before:')
print(RM, '\n')
with np.nditer(RM, op_flags=['readwrite'], flags=['multi_index']) as it:
    for x in it:
        A  = np.random.random()
        if A > 0.9:
            x[...] = 1 - x  # Flip
            print(f'Flip: <{it.multi_index}>,  {A:.3f}')
print('\nAfter:')
print(RM)

To get repeatable result, I added np.random.seed(0) (remove it in the
target version).

With the above seeding, I got the following result:

Before:
[[0 1 1 0 1 1 1 1 1 1]
 [1 0 0 1 0 0 0 0 0 1]
 [0 1 1 0 0 1 1 1 1 0]
 [1 0 1 0 1 1 0 1 1 0]
 [0 1 0 1 1 1 1 1 0 1]]

Flip: <(0, 2)>,  0.945
Flip: <(1, 3)>,  0.944
Flip: <(2, 7)>,  0.988
Flip: <(4, 5)>,  0.976
Flip: <(4, 7)>,  0.977

After:
[[0 1 0 0 1 1 1 1 1 1]
 [1 0 0 0 0 0 0 0 0 1]
 [0 1 1 0 0 1 1 0 1 0]
 [1 0 1 0 1 1 0 1 1 0]
 [0 1 0 1 1 0 1 0 0 1]]

Compare elements indicated as flipped, in "Before" and "After" sections,
to confirm that the above code does its job.
Check also that no other element has been changed.

A bit tricky element in the above code is x[...] = 1 - x.
Note that 1 - x part reads the current value (so far it is OK).
But if you attempted to save anything to x, writing x =,
then you would break the link to the source array element.
In this case x would point to the new value, but not to the
current array element.

So in order not to break this link, just x[...] = notation is needed.


来源: stackexchange

问:
find out object item names in as3
let's say you're passing an object to a function

```<code>{title:"my title", data:"corresponding data"}
</code>```

how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?

答:
You can use a for loop as follows:

```<code>for (var key:String in obj) {
    var value:String = obj[key];
    trace(key + ": " + value);
}
</code>```

Or use the introspection API.

The Flex 3 Help page on Performing Object Introspection has a good overview of these.

ContentLicense: CC BY-SA 3.0

Title: find out object item names in as3

Body:
let's say you're passing an object to a function

{title:"my title", data:"corresponding data"}

how can I get the function to know what the names of the items/sub-objects are (title and data) without specifying them?

Body:
You can use a for loop as follows:

for (var key:String in obj) {
    var value:String = obj[key];
    trace(key + ": " + value);
}

Or use the introspection API.

The Flex 3 Help page on Performing Object Introspection has a good overview of these.


问:
Couldn't connect to server 127.0.0.1:27017
I'm getting the following error:

```<code>alex@alex-K43U:/$ mongo
MongoDB shell version: 2.2.0
connecting to: test
Thu Oct 11 11:46:53 Error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js:91
exception: connect failed
alex@alex-K43U:/$
</code>```

This is what happens when I try to start mongodb:

```<code>* Starting database mongodb                                             [fail]
</code>```

I already tried mongo --repair

I made chown and chmod to var, lib, and data/db and log mongodb.

Not sure what else to do. Any suggestions?

mongodb.log:

```<code>***** SERVER RESTARTED *****

Thu Oct 11 08:29:40
Thu Oct 11 08:29:40 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Thu Oct 11 08:29:40
Thu Oct 11 08:29:41 [initandlisten] MongoDB starting : pid=1052 port=27017 dbpath=/var/lib/mongodb 32-bit host=alex-K43U
Thu Oct 11 08:29:41 [initandlisten]
Thu Oct 11 08:29:41 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Thu Oct 11 08:29:41 [initandlisten] **       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Oct 11 08:29:41 [initandlisten] **       with --journal, the limit is lower
Thu Oct 11 08:29:41 [initandlisten]
Thu Oct 11 08:29:41 [initandlisten] db version v2.2.0, pdfile version 4.5
Thu Oct 11 08:29:41 [initandlisten] git version: f5e83eae9cfbec7fb7a071321928f00d1b0c5207
Thu Oct 11 08:29:41 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_49
Thu Oct 11 08:29:41 [initandlisten] options: { config: "/etc/mongodb.conf", dbpath: "/var/lib/mongodb", logappend: "true", logpath: "/var/log/mongodb/mongodb.log" }
Thu Oct 11 08:29:41 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/var/lib/mongodb/journal"
**************
Unclean shutdown detected.
Please visit http://dochub.mongodb.org/core/repair for recovery instructions.
*************
Thu Oct 11 08:29:41 [initandlisten] exception in initAndListen: 12596 old lock file, terminating
Thu Oct 11 08:29:41 dbexit:
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to close listening sockets...
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to flush diaglog...
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to close sockets...
Thu Oct 11 08:29:41 [initandlisten] shutdown: waiting for fs preallocator...
Thu Oct 11 08:29:41 [initandlisten] shutdown: closing all files...
Thu Oct 11 08:29:41 [initandlisten] closeAllFiles() finished
Thu Oct 11 08:29:41 dbexit: really exiting now
</code>```

EDIT:

I removed the lock then did mongod repair and got this error:

```<code>Thu Oct 11 12:05:37 [initandlisten] exception in initAndListen: 10309 Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied Is a mongod instance already running?, terminating
</code>```

so I did it with sudo:

```<code>alex@alex-K43U:~$ sudo mongod --repair
Thu Oct 11 12:05:42
Thu Oct 11 12:05:42 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Thu Oct 11 12:05:42
Thu Oct 11 12:05:42 [initandlisten] MongoDB starting : pid=5129 port=27017 dbpath=/data/db/ 32-bit host=alex-K43U
Thu Oct 11 12:05:42 [initandlisten]
Thu Oct 11 12:05:42 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Thu Oct 11 12:05:42 [initandlisten] **       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Oct 11 12:05:42 [initandlisten] **       with --journal, the limit is lower
Thu Oct 11 12:05:42 [initandlisten]
Thu Oct 11 12:05:42 [initandlisten] db version v2.2.0, pdfile version 4.5
Thu Oct 11 12:05:42 [initandlisten] git version: f5e83eae9cfbec7fb7a071321928f00d1b0c5207
Thu Oct 11 12:05:42 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_49
Thu Oct 11 12:05:42 [initandlisten] options: { repair: true }
Thu Oct 11 12:05:42 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/data/db/journal"
Thu Oct 11 12:05:42 [initandlisten] finished checking dbs
Thu Oct 11 12:05:42 dbexit:
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to close listening sockets...
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to flush diaglog...
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to close sockets...
Thu Oct 11 12:05:42 [initandlisten] shutdown: waiting for fs preallocator...
Thu Oct 11 12:05:42 [initandlisten] shutdown: closing all files...
Thu Oct 11 12:05:42 [initandlisten] closeAllFiles() finished
Thu Oct 11 12:05:42 [initandlisten] shutdown: removing fs lock...
Thu Oct 11 12:05:42 dbexit: really exiting now
</code>```

But still having the same problem.

答:
Just try:</p>

```<code>sudo service mongod restart
</code>```

Body:
I'm getting the following error:

alex@alex-K43U:/$ mongo
MongoDB shell version: 2.2.0
connecting to: test
Thu Oct 11 11:46:53 Error: couldn't connect to server 127.0.0.1:27017 src/mongo/shell/mongo.js:91
exception: connect failed
alex@alex-K43U:/$

This is what happens when I try to start mongodb:

* Starting database mongodb                                             [fail]

I already tried mongo --repair

I made chown and chmod to var, lib, and data/db and log mongodb.

Not sure what else to do. Any suggestions?

mongodb.log:

***** SERVER RESTARTED *****

Thu Oct 11 08:29:40
Thu Oct 11 08:29:40 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Thu Oct 11 08:29:40
Thu Oct 11 08:29:41 [initandlisten] MongoDB starting : pid=1052 port=27017 dbpath=/var/lib/mongodb 32-bit host=alex-K43U
Thu Oct 11 08:29:41 [initandlisten]
Thu Oct 11 08:29:41 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Thu Oct 11 08:29:41 [initandlisten] **       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Oct 11 08:29:41 [initandlisten] **       with --journal, the limit is lower
Thu Oct 11 08:29:41 [initandlisten]
Thu Oct 11 08:29:41 [initandlisten] db version v2.2.0, pdfile version 4.5
Thu Oct 11 08:29:41 [initandlisten] git version: f5e83eae9cfbec7fb7a071321928f00d1b0c5207
Thu Oct 11 08:29:41 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_49
Thu Oct 11 08:29:41 [initandlisten] options: { config: "/etc/mongodb.conf", dbpath: "/var/lib/mongodb", logappend: "true", logpath: "/var/log/mongodb/mongodb.log" }
Thu Oct 11 08:29:41 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/var/lib/mongodb/journal"
**************
Unclean shutdown detected.
Please visit http://dochub.mongodb.org/core/repair for recovery instructions.
*************
Thu Oct 11 08:29:41 [initandlisten] exception in initAndListen: 12596 old lock file, terminating
Thu Oct 11 08:29:41 dbexit:
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to close listening sockets...
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to flush diaglog...
Thu Oct 11 08:29:41 [initandlisten] shutdown: going to close sockets...
Thu Oct 11 08:29:41 [initandlisten] shutdown: waiting for fs preallocator...
Thu Oct 11 08:29:41 [initandlisten] shutdown: closing all files...
Thu Oct 11 08:29:41 [initandlisten] closeAllFiles() finished
Thu Oct 11 08:29:41 dbexit: really exiting now

EDIT:

I removed the lock then did mongod repair and got this error:

Thu Oct 11 12:05:37 [initandlisten] exception in initAndListen: 10309 Unable to create/open lock file: /data/db/mongod.lock errno:13 Permission denied Is a mongod instance already running?, terminating

so I did it with sudo:

alex@alex-K43U:~$ sudo mongod --repair
Thu Oct 11 12:05:42
Thu Oct 11 12:05:42 warning: 32-bit servers don't have journaling enabled by default. Please use --journal if you want durability.
Thu Oct 11 12:05:42
Thu Oct 11 12:05:42 [initandlisten] MongoDB starting : pid=5129 port=27017 dbpath=/data/db/ 32-bit host=alex-K43U
Thu Oct 11 12:05:42 [initandlisten]
Thu Oct 11 12:05:42 [initandlisten] ** NOTE: when using MongoDB 32 bit, you are limited to about 2 gigabytes of data
Thu Oct 11 12:05:42 [initandlisten] **       see http://blog.mongodb.org/post/137788967/32-bit-limitations
Thu Oct 11 12:05:42 [initandlisten] **       with --journal, the limit is lower
Thu Oct 11 12:05:42 [initandlisten]
Thu Oct 11 12:05:42 [initandlisten] db version v2.2.0, pdfile version 4.5
Thu Oct 11 12:05:42 [initandlisten] git version: f5e83eae9cfbec7fb7a071321928f00d1b0c5207
Thu Oct 11 12:05:42 [initandlisten] build info: Linux domU-12-31-39-01-70-B4 2.6.21.7-2.fc8xen #1 SMP Fri Feb 15 12:39:36 EST 2008 i686 BOOST_LIB_VERSION=1_49
Thu Oct 11 12:05:42 [initandlisten] options: { repair: true }
Thu Oct 11 12:05:42 [initandlisten] Unable to check for journal files due to: boost::filesystem::basic_directory_iterator constructor: No such file or directory: "/data/db/journal"
Thu Oct 11 12:05:42 [initandlisten] finished checking dbs
Thu Oct 11 12:05:42 dbexit:
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to close listening sockets...
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to flush diaglog...
Thu Oct 11 12:05:42 [initandlisten] shutdown: going to close sockets...
Thu Oct 11 12:05:42 [initandlisten] shutdown: waiting for fs preallocator...
Thu Oct 11 12:05:42 [initandlisten] shutdown: closing all files...
Thu Oct 11 12:05:42 [initandlisten] closeAllFiles() finished
Thu Oct 11 12:05:42 [initandlisten] shutdown: removing fs lock...
Thu Oct 11 12:05:42 dbexit: really exiting now

But still having the same problem.

Body:
Just try:

sudo service mongod restart

ContentLicense: CC BY-SA 4.0


问:
Keycloak custom spi - custom transaction timeout
I am trying to do a sync process via the keycloak ImportSynchronization interface.
(wildlfy 18.0.1.Final)
it provides the following method to override:

```<code>    @Override
    public SynchronizationResult sync(
        final KeycloakSessionFactory sessionFactory,
        final String realmId,
        final UserStorageProviderModel model) {
    ...}
</code>```

This sync process takes much more time than our default transaction timeout (300 sec = 5 min).

I am aware of this possible opportunity:

```<code>            <core-environment node-identifier="${jboss.tx.node.id:1}">
                <process-id>
                    <uuid/>
                </process-id>
            </core-environment>
            <recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/>
            <coordinator-environment statistics-enabled="${wildfly.transactions.statistics-enabled:${wildfly.statistics-enabled:false}}"
                                     default-timeout="${env.TRANSACTION_TIMEOUT_SEC:300}"/>
            <object-store path="tx-object-store" relative-to="jboss.server.data.dir"/>
        </subsystem>
</code>```

BUT this is not what I want, unfortunately.

I don't want to increase the timeout for all of our processes, just for this one. Meaning I am searching for a custom transaction timeout solution. (something like @TransactionTimeout...)

I've tried the following

```<code>
@Override
    public SynchronizationResult doCleanup(final KeycloakSessionFactory keycloakSessionFactory, final String realmId)  {
        final SynchronizationResult synchronizationResult = new SynchronizationResult();

        try {

            final RealmModel realmModel = this.getRealmModelInTx(realmId, keycloakSessionFactory);

            Thread.sleep(<more than tx timeout>);

            final int userEntityCountBeforeCleanup = this.getUserCountInTx(realmModel, keycloakSessionFactory);
...}

</code>```

and in both methods, I created a new keycloakSession and a new transactionManager and closed them like here:

```<code>    private CleanupTransactionHandler createSession(final KeycloakSessionFactory  keycloakSessionFactory) {
        KeycloakTransactionManager transactionManager = null;
        final KeycloakSession keycloakSession = keycloakSessionFactory.create();

        log.tracef("KeycloakSession has been created [%s].", keycloakSession.hashCode());
        transactionManager = keycloakSession.getTransactionManager();
        transactionManager.begin();
        log.tracef("KeycloakTransactionManager's transaction has been begun [%s].", transactionManager.hashCode());
        return new CleanupTransactionHandler(keycloakSession,transactionManager);
    }

    private void closeSession(final KeycloakSession keycloakSession) {
        keycloakSession.close();
        log.tracef("KeycloakSession has been closed [%s].", keycloakSession.hashCode());
    }

    private void rollback(final KeycloakTransactionManager keycloakTransactionManager) {
        keycloakTransactionManager.rollback();
        log.tracef("KeycloakTransactionManager's transaction has been rolled back [%s].", keycloakTransactionManager.hashCode());
    }
</code>```

答:
I can answer my own answer.

There is no possibility to customize the transaction timeout for this process, since ImportSynchronization.sync is called from KeycloakModelUtils.runJobInTransaction, that can only configured via default-timeout as mentioned above.

Body:
I am trying to do a sync process via the keycloak ImportSynchronization interface.
(wildlfy 18.0.1.Final)
it provides the following method to override:

    @Override
    public SynchronizationResult sync(
        final KeycloakSessionFactory sessionFactory,
        final String realmId,
        final UserStorageProviderModel model) {
    ...}

This sync process takes much more time than our default transaction timeout (300 sec = 5 min).

I am aware of this possible opportunity:

            <core-environment node-identifier="${jboss.tx.node.id:1}">
                <process-id>
                    <uuid/>
                </process-id>
            </core-environment>
            <recovery-environment socket-binding="txn-recovery-environment" status-socket-binding="txn-status-manager"/>
            <coordinator-environment statistics-enabled="${wildfly.transactions.statistics-enabled:${wildfly.statistics-enabled:false}}"
                                     default-timeout="${env.TRANSACTION_TIMEOUT_SEC:300}"/>
            <object-store path="tx-object-store" relative-to="jboss.server.data.dir"/>
        </subsystem>

BUT this is not what I want, unfortunately.

I don't want to increase the timeout for all of our processes, just for this one. Meaning I am searching for a custom transaction timeout solution. (something like @TransactionTimeout...)

I've tried the following

@Override
    public SynchronizationResult doCleanup(final KeycloakSessionFactory keycloakSessionFactory, final String realmId)  {
        final SynchronizationResult synchronizationResult = new SynchronizationResult();

        try {

            final RealmModel realmModel = this.getRealmModelInTx(realmId, keycloakSessionFactory);

            Thread.sleep(<more than tx timeout>);

            final int userEntityCountBeforeCleanup = this.getUserCountInTx(realmModel, keycloakSessionFactory);
...}

and in both methods, I created a new keycloakSession and a new transactionManager and closed them like here:

    private CleanupTransactionHandler createSession(final KeycloakSessionFactory  keycloakSessionFactory) {
        KeycloakTransactionManager transactionManager = null;
        final KeycloakSession keycloakSession = keycloakSessionFactory.create();

        log.tracef("KeycloakSession has been created [%s].", keycloakSession.hashCode());
        transactionManager = keycloakSession.getTransactionManager();
        transactionManager.begin();
        log.tracef("KeycloakTransactionManager's transaction has been begun [%s].", transactionManager.hashCode());
        return new CleanupTransactionHandler(keycloakSession,transactionManager);
    }

    private void closeSession(final KeycloakSession keycloakSession) {
        keycloakSession.close();
        log.tracef("KeycloakSession has been closed [%s].", keycloakSession.hashCode());
    }

    private void rollback(final KeycloakTransactionManager keycloakTransactionManager) {
        keycloakTransactionManager.rollback();
        log.tracef("KeycloakTransactionManager's transaction has been rolled back [%s].", keycloakTransactionManager.hashCode());
    }


问:
Not doing the random pet, just giving the rarest every time. How do I fix it?
I am making a simulator game on roblox and it has a pet system. I revamped how the hatch works, and for some reason it started to glitch out, and always give the same pet, and the pet was always the rarest one. I don't know what the problem is, here is the script. The Weight system worked perfectly before, but now it isnt working. I compared it to the old version of the game and the only difference is what the variables are called.</p>

```<code>game.ReplicatedStorage.OpenEgg.OnServerInvoke = (function(player, amount, egg)
    print("Fired")
    if not player:FindFirstChild("Debounce") then
        if amount == "One" then
            local CC = player.leaderstats.CloudCoins
            local EO = player.leaderstats.EggsOpened
            local EGGS = require(game.ReplicatedStorage.EGGS)
            local Data = EGGS[egg]
            local Price = Data["Cost"]
            local Pets = Data["Pets"]
            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end
            local function GetChance(ChosenPet)
                for i, v in pairs(Pets)do
                    for o,b in pairs(Pets) do
                        if o == ChosenPet then
                            return b[1]
                        end
                    end
                end
            end
            if CC.Value >= Price then
                local ChosenPet = ChoosePet(player)
                local Chance = GetChance(ChosenPet)
                CC.Value = CC.Value - Price
                EO.Value = EO.Value + 1
                local Pet = Instance.new("BoolValue")
                Pet.Name = ChosenPet
                Pet.Parent = player.Pets
                if not player.PetsA:FindFirstChild(Pet.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                local Level = Instance.new("IntValue")
                local Xp = Instance.new("IntValue")
                local Number = Instance.new("IntValue")
                Number.Name = "Number"
                Number.Value = player.PetsA[Pet.Name.." Amount"].Value
                Number.Parent = Pet
                Level.Name = "Level"
                Xp.Name = "XP"
                Level.Value = 1
                Xp.Value = 0
                Level.Parent = Pet
                Xp.Parent = Pet
                return("Hatched")
            else
                return("NotEnoughCoins")
            end
        end
        if amount == "Triple" then
            local CC = player.leaderstats.CloudCoins
            local EO = player.leaderstats.EggsOpened
            local EGGS = require(game.ReplicatedStorage.EGGS)
            local Data = EGGS[egg]
            local Price = Data["Cost"]
            local Pets = Data["Pets"]
            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end
            local function GetChance(ChosenPet)
                for i, v in pairs(Pets)do
                    for o,b in pairs(Pets) do
                        if o == ChosenPet then
                            return b[1]
                        end
                    end
                end
            end
            if CC.Value >= Price*3 then
                local ChosenPet1,ChosenPet2,ChosenPet3 = ChoosePet(player),ChoosePet(player),ChoosePet(player)
                local Chance1,Chance2,Chance3 = GetChance(ChosenPet1),GetChance(ChosenPet2),GetChance(ChosenPet3)
                CC.Value = CC.Value - Price*3
                EO.Value = EO.Value + 3
                local Pet1 = Instance.new("BoolValue")
                Pet1.Name = ChosenPet1
                Pet1.Parent = player.Pets
                local Level1 = Instance.new("IntValue")
                local Xp1 = Instance.new("IntValue")
                local Number1 = Instance.new("IntValue")
                Number1.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet1.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet1.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet1.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number1.Value = player.PetsA[Pet1.Name.." Amount"].Value
                Number1.Parent = Pet1
                Level1.Name = "Level"
                Xp1.Name = "XP"
                Level1.Value = 1
                Xp1.Value = 0
                Level1.Parent = Pet1
                Xp1.Parent = Pet1
                local Pet2 = Instance.new("BoolValue")
                Pet2.Name = ChosenPet2
                Pet2.Parent = player.Pets
                local Level2 = Instance.new("IntValue")
                local Xp2 = Instance.new("IntValue")
                local Number2 = Instance.new("IntValue")
                Number2.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet2.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet2.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet2.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number2.Value = player.PetsA[Pet2.Name.." Amount"].Value
                Number2.Parent = Pet2
                Level2.Name = "Level"
                Xp2.Name = "XP"
                Level2.Value = 1
                Xp2.Value = 0
                Level2.Parent = Pet2
                Xp2.Parent = Pet2
                local Pet3 = Instance.new("BoolValue")
                Pet3.Name = ChosenPet3
                Pet3.Parent = player.Pets
                local Level3 = Instance.new("IntValue")
                local Xp3 = Instance.new("IntValue")
                local Number3 = Instance.new("IntValue")
                Number3.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet3.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet3.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet3.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number3.Value = player.PetsA[Pet3.Name.." Amount"].Value
                Number3.Parent = Pet3
                Level3.Name = "Level"
                Xp3.Name = "XP"
                Level3.Value = 1
                Xp3.Value = 0
                Level3.Parent = Pet3
                Xp3.Parent = Pet3
                return("Hatched")
            else
                return("NotEnoughCoins")
            end
        end
    end
end)
</code>```

答:
take a closer look at these lines of code.

            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end
```

the next time we see this function it is to assign the chosen pet to the player. I would suggest playing around with the Chance value. Set it to something crazy and see if you get another pet instead.

Body:
I am making a simulator game on roblox and it has a pet system. I revamped how the hatch works, and for some reason it started to glitch out, and always give the same pet, and the pet was always the rarest one. I don't know what the problem is, here is the script. The Weight system worked perfectly before, but now it isnt working. I compared it to the old version of the game and the only difference is what the variables are called.

game.ReplicatedStorage.OpenEgg.OnServerInvoke = (function(player, amount, egg)
    print("Fired")
    if not player:FindFirstChild("Debounce") then
        if amount == "One" then
            local CC = player.leaderstats.CloudCoins
            local EO = player.leaderstats.EggsOpened
            local EGGS = require(game.ReplicatedStorage.EGGS)
            local Data = EGGS[egg]
            local Price = Data["Cost"]
            local Pets = Data["Pets"]
            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end
            local function GetChance(ChosenPet)
                for i, v in pairs(Pets)do
                    for o,b in pairs(Pets) do
                        if o == ChosenPet then
                            return b[1]
                        end
                    end
                end
            end
            if CC.Value >= Price then
                local ChosenPet = ChoosePet(player)
                local Chance = GetChance(ChosenPet)
                CC.Value = CC.Value - Price
                EO.Value = EO.Value + 1
                local Pet = Instance.new("BoolValue")
                Pet.Name = ChosenPet
                Pet.Parent = player.Pets
                if not player.PetsA:FindFirstChild(Pet.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                local Level = Instance.new("IntValue")
                local Xp = Instance.new("IntValue")
                local Number = Instance.new("IntValue")
                Number.Name = "Number"
                Number.Value = player.PetsA[Pet.Name.." Amount"].Value
                Number.Parent = Pet
                Level.Name = "Level"
                Xp.Name = "XP"
                Level.Value = 1
                Xp.Value = 0
                Level.Parent = Pet
                Xp.Parent = Pet
                return("Hatched")
            else
                return("NotEnoughCoins")
            end
        end
        if amount == "Triple" then
            local CC = player.leaderstats.CloudCoins
            local EO = player.leaderstats.EggsOpened
            local EGGS = require(game.ReplicatedStorage.EGGS)
            local Data = EGGS[egg]
            local Price = Data["Cost"]
            local Pets = Data["Pets"]
            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end
            local function GetChance(ChosenPet)
                for i, v in pairs(Pets)do
                    for o,b in pairs(Pets) do
                        if o == ChosenPet then
                            return b[1]
                        end
                    end
                end
            end
            if CC.Value >= Price*3 then
                local ChosenPet1,ChosenPet2,ChosenPet3 = ChoosePet(player),ChoosePet(player),ChoosePet(player)
                local Chance1,Chance2,Chance3 = GetChance(ChosenPet1),GetChance(ChosenPet2),GetChance(ChosenPet3)
                CC.Value = CC.Value - Price*3
                EO.Value = EO.Value + 3
                local Pet1 = Instance.new("BoolValue")
                Pet1.Name = ChosenPet1
                Pet1.Parent = player.Pets
                local Level1 = Instance.new("IntValue")
                local Xp1 = Instance.new("IntValue")
                local Number1 = Instance.new("IntValue")
                Number1.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet1.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet1.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet1.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number1.Value = player.PetsA[Pet1.Name.." Amount"].Value
                Number1.Parent = Pet1
                Level1.Name = "Level"
                Xp1.Name = "XP"
                Level1.Value = 1
                Xp1.Value = 0
                Level1.Parent = Pet1
                Xp1.Parent = Pet1
                local Pet2 = Instance.new("BoolValue")
                Pet2.Name = ChosenPet2
                Pet2.Parent = player.Pets
                local Level2 = Instance.new("IntValue")
                local Xp2 = Instance.new("IntValue")
                local Number2 = Instance.new("IntValue")
                Number2.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet2.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet2.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet2.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number2.Value = player.PetsA[Pet2.Name.." Amount"].Value
                Number2.Parent = Pet2
                Level2.Name = "Level"
                Xp2.Name = "XP"
                Level2.Value = 1
                Xp2.Value = 0
                Level2.Parent = Pet2
                Xp2.Parent = Pet2
                local Pet3 = Instance.new("BoolValue")
                Pet3.Name = ChosenPet3
                Pet3.Parent = player.Pets
                local Level3 = Instance.new("IntValue")
                local Xp3 = Instance.new("IntValue")
                local Number3 = Instance.new("IntValue")
                Number3.Name = "Number"
                if not player.PetsA:FindFirstChild(Pet3.Name.." Amount") then
                    local AmountA = Instance.new("IntValue")
                    AmountA.Name = Pet3.Name.." Amount"
                    AmountA.Value = 1
                else
                    local AmountA = player.PetsA[Pet3.Name.." Amount"]
                    AmountA.Value = AmountA.Value + 1
                end
                Number3.Value = player.PetsA[Pet3.Name.." Amount"].Value
                Number3.Parent = Pet3
                Level3.Name = "Level"
                Xp3.Name = "XP"
                Level3.Value = 1
                Xp3.Value = 0
                Level3.Parent = Pet3
                Xp3.Parent = Pet3
                return("Hatched")
            else
                return("NotEnoughCoins")
            end
        end
    end
end)

Body:
take a closer look at these lines of code.

            local TotalWeight = 0
            for i,v in pairs(Pets) do
                TotalWeight = TotalWeight + v[1]
            end
            local function ChoosePet(player)
                local Chance = math.random(1,TotalWeight)
                local Counter = 0
                for d,c in pairs(Pets)do
                    Counter = Counter + c[1]
                    if Chance >= Counter then
                        return d
                    end
                end
            end

the next time we see this function it is to assign the chosen pet to the player. I would suggest playing around with the Chance value. Set it to something crazy and see if you get another pet instead.


问:
Create/insert event (Google Calendar API v3) via HTTP Post > "400: Missing end time"
I am using FileMaker to interact with the Google Calendar API. I have managed to authorize my app, get a list of user's calendars and a list of events in those calendars and details for those events. However, I am having trouble creating events.

I make the following HTTP POST request. Header: Content-Type : application/json, Authorization : Bearer access_token

https://www.googleapis.com/calendar/v3/calendars/**********@gmail.com/events?{"attachments":[{"fileUrl":""}],"attendees":[{"email":"***********@gmail.com"}],"end":{"dateTime":"2017-08-20T13:00:00-05:00"},"reminders":{"useDefault":true},"start":{"dateTime":"2017-08-20T12:00:00-05:00"},"summary":"Test Event"}

I receive the following JSON error response:

```<code>{
    "error":
    {
        "errors":
            [
                {
                    "domain": "global",
                    "reason": "required",
                    "message": "Missing end time."
                }
            ],
        "code": 400,
        "message": "Missing end time."
    }
}
</code>```

It appears that this is a pretty common error that people run into. However it looks like most having this problem are using frameworks for which there are libraries that Google Calendar API supports. I've tried to pick out the fix from some of the posts on stackoverflow and elsewhere concerning these other frameworks and apply them to my FileMaker / HTTP GET/POST setup to no avail.

Any help greatly appreciated!

答:
Use this</p>

```<code>curl --location --request POST 'https://www.googleapis.com/calendar/v3/calendars/{email}/events' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {access_token}' \
--header 'Content-Type: text/plain' \
--data-raw '{`enter code here`
  "summary": "Google I/O 2015",
  "location": "800 Howard St., San Francisco, CA 94103",
  "description": "A chance to hear more about Google'\''s developer products.",
  "start": {
    "dateTime": "2015-05-28T09:00:00-07:00",
    "timeZone": "America/Los_Angeles"},
  "end": {
    "dateTime": "2015-05-28T17:00:00-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "recurrence": [
    "RRULE:FREQ=DAILY;COUNT=2"
  ],
  "attendees": [
    {"email": "lpage@example.com"},
    {"email": "sbrin@example.com"}
  ],
  "reminders": {
    "useDefault": false,
    "overrides": [
      {"method": "email", "minutes": 24},
      {"method": "popup", "minutes": 10}
    ]
  }
}'
</code>```

Body:
I am using FileMaker to interact with the Google Calendar API. I have managed to authorize my app, get a list of user's calendars and a list of events in those calendars and details for those events. However, I am having trouble creating events.

I make the following HTTP POST request. Header: Content-Type : application/json, Authorization : Bearer access_token

https://www.googleapis.com/calendar/v3/calendars/**********@gmail.com/events?{"attachments":[{"fileUrl":""}],"attendees":[{"email":"***********@gmail.com"}],"end":{"dateTime":"2017-08-20T13:00:00-05:00"},"reminders":{"useDefault":true},"start":{"dateTime":"2017-08-20T12:00:00-05:00"},"summary":"Test Event"}

I receive the following JSON error response:

{
    "error":
    {
        "errors":
            [
                {
                    "domain": "global",
                    "reason": "required",
                    "message": "Missing end time."
                }
            ],
        "code": 400,
        "message": "Missing end time."
    }
}

It appears that this is a pretty common error that people run into. However it looks like most having this problem are using frameworks for which there are libraries that Google Calendar API supports. I've tried to pick out the fix from some of the posts on stackoverflow and elsewhere concerning these other frameworks and apply them to my FileMaker / HTTP GET/POST setup to no avail.

Any help greatly appreciated!

Body:
Use this

curl --location --request POST 'https://www.googleapis.com/calendar/v3/calendars/{email}/events' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer {access_token}' \
--header 'Content-Type: text/plain' \
--data-raw '{`enter code here`
  "summary": "Google I/O 2015",
  "location": "800 Howard St., San Francisco, CA 94103",
  "description": "A chance to hear more about Google'\''s developer products.",
  "start": {
    "dateTime": "2015-05-28T09:00:00-07:00",
    "timeZone": "America/Los_Angeles"},
  "end": {
    "dateTime": "2015-05-28T17:00:00-07:00",
    "timeZone": "America/Los_Angeles"
  },
  "recurrence": [
    "RRULE:FREQ=DAILY;COUNT=2"
  ],
  "attendees": [
    {"email": "lpage@example.com"},
    {"email": "sbrin@example.com"}
  ],
  "reminders": {
    "useDefault": false,
    "overrides": [
      {"method": "email", "minutes": 24},
      {"method": "popup", "minutes": 10}
    ]
  }
}'


问:
DRF: Do DRF serializers, SerializerMethodField have execution order
```<code>class ProfileAPI(serializers.Serializer):
    name = serializers.SerializerMethodField()
    age = serializers.SerializerMethodField()

    def get_name(self, obj):
        return "name"

    def age(self,obj):
        return 78
</code>```

is there ordering while execution of SerilaizerMethodField or it is random, means will "get_name" is executed before "get_age".

答:
The execution ordering goes by the order of fields in meta.

```<code>class ProfileAPI(serializers.Serializer):
    name = serializers.SerializerMethodField()
    age = serializers.SerializerMethodField()

    def get_name(self, obj):
        return "name"

    def age(self,obj):
        return 78

    class Meta:
        fields = ["name", "age"]
</code>```

In the above case "get_name" is called first and then "get_age".

changing the order to

```<code>class Meta:
     fields = ["age", "name"]
</code>```

would execute get_age first.

Body:
class ProfileAPI(serializers.Serializer):
    name = serializers.SerializerMethodField()
    age = serializers.SerializerMethodField()

    def get_name(self, obj):
        return "name"

    def age(self,obj):
        return 78

is there ordering while execution of SerilaizerMethodField or it is random, means will "get_name" is executed before "get_age".

Body:
The execution ordering goes by the order of fields in meta.

class ProfileAPI(serializers.Serializer):
    name = serializers.SerializerMethodField()
    age = serializers.SerializerMethodField()

    def get_name(self, obj):
        return "name"

    def age(self,obj):
        return 78

    class Meta:
        fields = ["name", "age"]

In the above case "get_name" is called first and then "get_age".

changing the order to

class Meta:
     fields = ["age", "name"]

would execute get_age first.


问:
Can't change divs ID of first element from <tempate>
I have this HTML template:

```<code><template id="single_feed">

    <div class="ibox" id="FIRST_DIV">
        <div class="ibox-title">
            <h5 id="naslov"></h5>
         </div>
        <div class="ibox-content">
            <form method="get" _lpchecked="1">
                 <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label>
            </form>
        </div>
    </div>
</template>
</code>```

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

```<code>    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});
</code>```

P.S:
I removed unnecessary parts to make code more readable.

答:
jQuery has .html() function to retrieve the inner html and .clone() function to clone the element. You can use both to achieve what you want and make the code more readable.

See this example (I have changed some values to make the example clearer):

let clicked = 0;

$(".btn-RSS-single").click(function(e) {
  var idClicked = e.target.id;
  idClicked = clicked++;

  const template = $("#single_feed").html();
  $template = jQuery(template).clone().attr("id", "NEW_ID_" + idClicked);

  $('#kolona_1').append($template);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#kolona_1 {
  border: 1px solid gray;
}

#kolona_1 > div {
    background-color: rgba(180, 180, 180, 0.2);
    margin: 1em;
  }

.btn-RSS-single {
  background-color: lightblue;
  padding: 0.2em 1em;
  text-align: center;
  cursor: pointer;
}</code>```

ADD

<template id="single_feed">

      <form method="get" _lpchecked="1">

Naziv

      </form>

</template>```

Body:
I have this HTML template:

<template id="single_feed">

            <form method="get" _lpchecked="1">

Naziv
            </form>

</template>

Now I want to clone and change first div ID (now set to: "FIRST_DIV"). But don't know how. I am able only to change 2nd,3rd.... divs.

My jquery code for cloning is:

    $(".btn-RSS-single").click(function(e) {
        var idClicked = e.target.id;

        const $template = $( $('#single_feed')[0].innerHTML );

        $template.find("div:first").attr("id", "NEW_ID_"+idClicked);

        $('#kolona_1').append($template);

});

P.S:
I removed unnecessary parts to make code more readable.

Body:
jQuery has .html() function to retrieve the inner html and .clone() function to clone the element. You can use both to achieve what you want and make the code more readable.

See this example (I have changed some values to make the example clearer):

let clicked = 0;

$(".btn-RSS-single").click(function(e) {
  var idClicked = e.target.id;
  idClicked = clicked++;

  const template = $("#single_feed").html();
  $template = jQuery(template).clone().attr("id", "NEW_ID_" + idClicked);

  $('#kolona_1').append($template);
});

#kolona_1 {
  border: 1px solid gray;
}

#kolona_1 > div {
    background-color: rgba(180, 180, 180, 0.2);
    margin: 1em;
  }

.btn-RSS-single {
  background-color: lightblue;
  padding: 0.2em 1em;
  text-align: center;
  cursor: pointer;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="kolona_1"></div>
<div class="btn-RSS-single">ADD</div>
<template id="single_feed">
  <div class="ibox" id="FIRST_DIV">
    <div class="ibox-title">
      <h5 id="naslov"></h5>
    </div>
    <div class="ibox-content">
      <form method="get" _lpchecked="1">
        <div class="form-group  row"><label class="col-sm-2 col-form-label">Naziv</label></div>
      </form>
    </div>
  </div>
</template>


问:
Updating value of star on second click using jQuery and ajax
I am working on star rating system which is my part of my project. The rating is stored in my database whenever the user rates by clicking on stars along with user bio data. Now, as we know, sometimes, when user rates any product, his/her mind can change at a moment and want to update rating. This is problem which I am currently facing. Whenever the user is giving a rating, it is stored, but when the same user gives a rating again, it again saves the value instead of updating the existing value. Please help me. I have to submit my proj at 8 june.

Here is my jQuery code:

```<code>$(document).ready(function(){

 load_business_data();

 function load_business_data()
 {
  $.ajax({
   url:"m.php",
   method:"POST",
   success:function(data)
   {
    $('#business_list').html(data);
   }
  });
 }

 $(document).on('mouseenter', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  remove_background(business_id);
  for(var count = 1; count<=index; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

 function remove_background(business_id)
 {
  for(var count = 1; count <= 5; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ccc');
  }
 }

 $(document).on('mouseleave', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  var rating = $(this).data("rating");
  remove_background(business_id);
  //alert(rating);
  for(var count = 1; count<=rating; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

 $(document).on('click', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
var username='<?php echo $_SESSION["username"];?>';
var useremail='<?php echo $_SESSION["useremail"];?>';

  $.ajax({
   url:"insert_rating.php",
   method:"POST",
   data:{index:index, business_id:business_id, username:username, useremail:useremail},
   success:function(data)
   {
if(data == 'done')
    {
       alert("There is some problem in System");
    }
    else
    {
 load_business_data();
     alert("Dear "+username+",You have rate "+index +" out of 5");

    }
   }
  });

 });

});
</script>
here is my pdo code use to insert query
<?php

//insert_rating.php
session_start();
$connect = new PDO('mysql:host=localhost;dbname=final', 'root', '');

if(isset($_POST["index"], $_POST["business_id"], $_POST["username"], $_POST["useremail"]))
{
 $query = "
 INSERT INTO rating(business_id, rating, username,useremail)
 VALUES (:business_id, :rating, :username, :useremail)
 ";
  $statement = $connect->prepare($query);
      $statement->execute(
  array(
   ':business_id'  => $_POST["business_id"],
   ':rating'   => $_POST["index"],
':username'   => $_POST["username"],
':useremail'   => $_POST["useremail"],
  )
);
 $result = $statement->fetchAll();
 if(isset($result))
 {
echo 'done';

?>
</code>```

答:
Firstly you need to check if the user already added his rating, to do this you have to count the rating according to the session username or id, if his rating already exists in database then you write update query else write insert query.
Here's a simple demonstration for doing this:

```<code>$stmt = $connect->prepare("SELECT * FROM `rating` WHERE ''");//add your conditions here according to user and that particular rating
$ifExists = $stmt->rowCount();
if ($ifExists == 0) {
  //write your insert query here
} else {
  //write update query here
}
</code>```

I hope it'll help you, if you need to be more clear, comment below

Body:
I am working on star rating system which is my part of my project. The rating is stored in my database whenever the user rates by clicking on stars along with user bio data. Now, as we know, sometimes, when user rates any product, his/her mind can change at a moment and want to update rating. This is problem which I am currently facing. Whenever the user is giving a rating, it is stored, but when the same user gives a rating again, it again saves the value instead of updating the existing value. Please help me. I have to submit my proj at 8 june.

Here is my jQuery code:

$(document).ready(function(){

 load_business_data();

 function load_business_data()
 {
  $.ajax({
   url:"m.php",
   method:"POST",
   success:function(data)
   {
    $('#business_list').html(data);
   }
  });
 }

 $(document).on('mouseenter', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  remove_background(business_id);
  for(var count = 1; count<=index; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

 function remove_background(business_id)
 {
  for(var count = 1; count <= 5; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ccc');
  }
 }

 $(document).on('mouseleave', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
  var rating = $(this).data("rating");
  remove_background(business_id);
  //alert(rating);
  for(var count = 1; count<=rating; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

 $(document).on('click', '.rating', function(){
  var index = $(this).data("index");
  var business_id = $(this).data('business_id');
var username='<?php echo $_SESSION["username"];?>';
var useremail='<?php echo $_SESSION["useremail"];?>';

  $.ajax({
   url:"insert_rating.php",
   method:"POST",
   data:{index:index, business_id:business_id, username:username, useremail:useremail},
   success:function(data)
   {
if(data == 'done')
    {
       alert("There is some problem in System");
    }
    else
    {
 load_business_data();
     alert("Dear "+username+",You have rate "+index +" out of 5");

    }
   }
  });

 });

});
</script>
here is my pdo code use to insert query
<?php

//insert_rating.php
session_start();
$connect = new PDO('mysql:host=localhost;dbname=final', 'root', '');

if(isset($_POST["index"], $_POST["business_id"], $_POST["username"], $_POST["useremail"]))
{
 $query = "
 INSERT INTO rating(business_id, rating, username,useremail)
 VALUES (:business_id, :rating, :username, :useremail)
 ";
  $statement = $connect->prepare($query);
      $statement->execute(
  array(
   ':business_id'  => $_POST["business_id"],
   ':rating'   => $_POST["index"],
':username'   => $_POST["username"],
':useremail'   => $_POST["useremail"],
  )
);
 $result = $statement->fetchAll();
 if(isset($result))
 {
echo 'done';

?>

Body:
Firstly you need to check if the user already added his rating, to do this you have to count the rating according to the session username or id, if his rating already exists in database then you write update query else write insert query.
Here's a simple demonstration for doing this:

$stmt = $connect->prepare("SELECT * FROM `rating` WHERE ''");//add your conditions here according to user and that particular rating
$ifExists = $stmt->rowCount();
if ($ifExists == 0) {
  //write your insert query here
} else {
  //write update query here
}

I hope it'll help you, if you need to be more clear, comment below


问:
Convert gregorian date to persian(jalali) date in angular 2 and Ionic 2
I'm familiar with one package located in npm for converting gregorian date to persian (jalali), but i don't know how should i use it in ionic 2 angular 2 projects.

Jalali-date

or this package for angular 1:

ADM-dateTimePicker

is it possible to convert this package to angular 2? any idea? or tutorial are welcome...

答:
There's no need to use any package. You can use toLocaleDateString method.

It's so simple:

var d = new Date();
console.info(d.toLocaleDateString("fa-IR"))
```
<p>The output will be something like <code>۱۳۹۹/۳/۱۰</code></p>
<p>But you can use options to get it a better look! For example:</p>
<pre class="lang-js prettyprint-override"><code>const options = { year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options))
// output> ۱۰ خرداد ۱۳۹۹
</code>```

Note: if you change direction to rtl it looks properly!

And for another example:

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options))
// output> ۱۳۹۹ خرداد ۱۰, شنبه
```
<blockquote>
<p><strong>Again:</strong> you must use <code>rtl</code> direction to see it in proper way!</p>
</blockquote>
<p>You can also use Intl.toLocaleTimeString for showing time. Like this:</p>
<pre class="lang-js prettyprint-override"><code>console.info(d.toLocaleDateString("fa-IR"));
// output> ۱۶:۰۶:۰۰

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options));
// output> ۱۳۹۹ خرداد ۱۰, شنبه، ۱۶:۰۴:۱۶
</code>```

For the last time! Don't forget rtl direction.

Body:
There's no need to use any package. You can use toLocaleDateString method.

It's so simple:

var d = new Date();
console.info(d.toLocaleDateString("fa-IR"))

The output will be something like ۱۳۹۹/۳/۱۰

But you can use options to get it a better look! For example:

const options = { year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options))
// output> ۱۰ خرداد ۱۳۹۹

Note: if you change direction to rtl it looks properly!

And for another example:

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options))
// output> ۱۳۹۹ خرداد ۱۰, شنبه

Again: you must use rtl direction to see it in proper way!

You can also use Intl.toLocaleTimeString for showing time. Like this:

console.info(d.toLocaleDateString("fa-IR"));
// output> ۱۶:۰۶:۰۰

const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.info(d.toLocaleDateString("fa-IR", options));
// output> ۱۳۹۹ خرداد ۱۰, شنبه، ۱۶:۰۴:۱۶

For the last time! Don't forget rtl direction.


问:
Cannot send message without a sender address in laravel 5.4
In my Laravel 5.4 app I want to send an email notification to the user when they signup I have set everything but not work and shown an exception like:

```<code>Cannot send message without a sender address
</code>```

I am using mailtrap.

I have also run the artisan command php artisan config:cache and php artisan cache:clear

This is my .env file:

```<code>MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=3e917ca6b3dabc
MAIL_PASSWORD=05abe282eca67f
MAIL_ENCRYPTION=tls
</code>```

答:
I think you didn't restart your service. You should restart your service by 2 steps:

Step 1: Stop your service (CMD):

```<code>Ctrl + C
</code>```

Step 2: You run service again:

```<code>npm run dev
php artisan serve
</code>```

Body:
In my Laravel 5.4 app I want to send an email notification to the user when they signup I have set everything but not work and shown an exception like:

Cannot send message without a sender address

I am using mailtrap.

I have also run the artisan command php artisan config:cache and php artisan cache:clear

This is my .env file:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=3e917ca6b3dabc
MAIL_PASSWORD=05abe282eca67f
MAIL_ENCRYPTION=tls

Body:
I think you didn't restart your service. You should restart your service by 2 steps:

Step 1: Stop your service (CMD):

Ctrl + C

Step 2: You run service again:

npm run dev
php artisan serve


问:
Verilog cannot synthesize when using external counter inside generate block
I cannot synthesize the Verilog code in Vivado, simulation runs correctly. I declare an array localparam, use an external counting variable cnt1 inside a generate block to get the desired address for parameter. When I remove the cnt1 variable inside module1, it could be synthesized. Please guys give me some suggestion to solve this problem. I really appreciate that.

```<code>module multiply_s1(
input clk,
input rst,
input [9:0]in,
input ena,

output [9:0]out);

localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0) begin
        cnt1 <= 0;
    end
    else if(ena == 0) begin
        cnt1 <= 0;
    end
    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i*5 +: 5]),
                     .multiplicand(pi_values[(i + cnt1)*5 +: 5]),
                     .result(out[i*5 +: 5]));
   end
endgenerate
</code>```

endmodule

答:
Notice here:

```<code>    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end
</code>```

It can be either 0, 1, 2 or 3. This works fine in simulation. But in synthesis, you are constantly changing the value of cnt1 while trying to build logic gates for mod1 where mod1 uses that changing variable cnt1. This is a conflict for synthesizing logic gates.

Synthesis can't build gates for your generate block as it is building actual hardware and wants to know a deterministic value of cnt1 in order to construct the gates accordingly.

I believe you need to develop an architecture that can handle the largest value of cnt1

Body:
I cannot synthesize the Verilog code in Vivado, simulation runs correctly. I declare an array localparam, use an external counting variable cnt1 inside a generate block to get the desired address for parameter. When I remove the cnt1 variable inside module1, it could be synthesized. Please guys give me some suggestion to solve this problem. I really appreciate that.

module multiply_s1(
input clk,
input rst,
input [9:0]in,
input ena,

output [9:0]out);

localparam [0:24] pi_values = {5'h4, 5'h5, 5'h6, 5'h7, 5'h8};
reg [1:0] cnt1;//count CC times of GG coeffcient

always@(posedge clk or negedge rst) begin
    if(rst == 0) begin
        cnt1 <= 0;
    end
    else if(ena == 0) begin
        cnt1 <= 0;
    end
    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end
end

genvar i;
generate
    for (i=0; i<2; i=i+1)
    begin: mod1
        module1 mod1(.clk(clk),
                     .rst(rst),
                     .multiplier(in[i*5 +: 5]),
                     .multiplicand(pi_values[(i + cnt1)*5 +: 5]),
                     .result(out[i*5 +: 5]));
   end
endgenerate

endmodule

Body:
Notice here:

    else begin
        if (cnt1 == 3)
            cnt1 <= 0;
        else
            cnt1 <= cnt1 + 1;
    end

It can be either 0, 1, 2 or 3. This works fine in simulation. But in synthesis, you are constantly changing the value of cnt1 while trying to build logic gates for mod1 where mod1 uses that changing variable cnt1. This is a conflict for synthesizing logic gates.

Synthesis can't build gates for your generate block as it is building actual hardware and wants to know a deterministic value of cnt1 in order to construct the gates accordingly.

I believe you need to develop an architecture that can handle the largest value of cnt1


问:
How do I store a checkbox value as yes in MySql Database - PHP
So when a user creates an account and they have to tick the checkbox to proceed which works, but how do I store that they accepted it (even though they cannot make an account without accpecting it). But we want to store it nonetheless.

Checkbox

```<code><input type="checkbox" name="agree" value="accepted">
</code>```

PHP

```<code>if ($_POST['agree'] != 'accepted') {
             $error[] = 'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy';
    } else {
            $stmt = $db->prepare('SELECT termsAccepted FROM members WHERE termsAccepted = :??????');
    $stmt->execute(array(':??????' => $?????));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    }
</code>```

答:
If the checkbox isn't checked, there wont be any agree index in the $_POST variable so check its existence beforehand to prevent throwing warnings in the log.

After that you can use an UPDATE query to modify the column termsAccepted in your members table.

pseudo code:

```<code>if (isset($_POST['agree']) && $_POST['agree'] == 'accepted') {
    $stmt = $db->prepare('UPDATE members SET termsAccepted=1 WHERE id = :user_id');
    $stmt->execute(array(':user_id' => $user_id));
}
</code>```

Tip: If you're only storing true or false, you can use the datatype TINYINT(1) or BOOLEAN for the column termsAccepted as it stores only two states.

Body:
So when a user creates an account and they have to tick the checkbox to proceed which works, but how do I store that they accepted it (even though they cannot make an account without accpecting it). But we want to store it nonetheless.

Checkbox

<input type="checkbox" name="agree" value="accepted">

PHP

if ($_POST['agree'] != 'accepted') {
             $error[] = 'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy';
    } else {
            $stmt = $db->prepare('SELECT termsAccepted FROM members WHERE termsAccepted = :??????');
    $stmt->execute(array(':??????' => $?????));
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    }

Body:
If the checkbox isn't checked, there wont be any agree index in the $_POST variable so check its existence beforehand to prevent throwing warnings in the log.

After that you can use an UPDATE query to modify the column termsAccepted in your members table.

pseudo code:

if (isset($_POST['agree']) && $_POST['agree'] == 'accepted') {
    $stmt = $db->prepare('UPDATE members SET termsAccepted=1 WHERE id = :user_id');
    $stmt->execute(array(':user_id' => $user_id));
}

Tip: If you're only storing true or false, you can use the datatype TINYINT(1) or BOOLEAN for the column termsAccepted as it stores only two states.


问:
Row-wise data reading in Python using openpyxl
I am trying to obtain a list in python by the format [[a,b], [c,d],...]

As an example, for two columns below in excel:

```<code>     R1   R2
     1    2
     6    2
     0    9
     3    2
     4    1
     5    6
</code>```

I should obtain a list = [[1,2], [6,2], [0, 9], [3,2], [4,1], [5,6]]

The code I have is shown below:

```<code>    R = []
    # iterate over column
    for col in range(min_column+3, max_column+1): #location of the data
    # u_need reads in the resource needed for each activity
      u_need = []
      # iterate over row
      for row in range(2, max_row+1): #row 1 is not included
         # loop until blank space is encountered
         if (sheet.cell(row,col).value is not None):
             u_need.append(sheet.cell(row,col).value);

      R.append(u_need)

    print(f'R = {R}')
</code>```

but the result gives me something like this:

```<code>    R = [[1, 6, 0, 3, 4, 5], [2, 2, 9, 2, 1, 6]]
</code>```

Is there a way I could change this? Any help would be appreciated! Thanks!

答:
I am using xlrd package to read the excel worksheets</p>

```<code>import xlrd

# my own excel sheet location which contains your data
loc = "a.xlsx"

# opening workbook
wb = xlrd.open_workbook(loc)
# selecting the first worksheet
sheet = wb.sheet_by_index(0)
lst = []
# not including the first row
for i in range(1,sheet.nrows):
    dummy = []
    for j in range(sheet.ncols):
        # appending the columns with the same row to dummy list
        dummy.append(sheet.cell_value(i, j))
    # appending the dummy list to the main list
    lst.append(dummy)
print(f"lst = {lst}") # output  lst = [[1.0, 2.0], [6.0, 2.0], [0.0, 9.0], [3.0, 2.0], [4.0, 1.0], [5.0, 6.0]]
</code>```

Body:
I am trying to obtain a list in python by the format [[a,b], [c,d],...]

As an example, for two columns below in excel:

     R1   R2
     1    2
     6    2
     0    9
     3    2
     4    1
     5    6

I should obtain a list = [[1,2], [6,2], [0, 9], [3,2], [4,1], [5,6]]

The code I have is shown below:

    R = []
    # iterate over column
    for col in range(min_column+3, max_column+1): #location of the data
    # u_need reads in the resource needed for each activity
      u_need = []
      # iterate over row
      for row in range(2, max_row+1): #row 1 is not included
         # loop until blank space is encountered
         if (sheet.cell(row,col).value is not None):
             u_need.append(sheet.cell(row,col).value);

      R.append(u_need)

    print(f'R = {R}')

but the result gives me something like this:

    R = [[1, 6, 0, 3, 4, 5], [2, 2, 9, 2, 1, 6]]

Is there a way I could change this? Any help would be appreciated! Thanks!

Body:
I am using xlrd package to read the excel worksheets

import xlrd

# my own excel sheet location which contains your data
loc = "a.xlsx"

# opening workbook
wb = xlrd.open_workbook(loc)
# selecting the first worksheet
sheet = wb.sheet_by_index(0)
lst = []
# not including the first row
for i in range(1,sheet.nrows):
    dummy = []
    for j in range(sheet.ncols):
        # appending the columns with the same row to dummy list
        dummy.append(sheet.cell_value(i, j))
    # appending the dummy list to the main list
    lst.append(dummy)
print(f"lst = {lst}") # output  lst = [[1.0, 2.0], [6.0, 2.0], [0.0, 9.0], [3.0, 2.0], [4.0, 1.0], [5.0, 6.0]]


问:
Java 5-compiled binaries on Java 1.3 runtime
May I know if there are any issues running a Java 5-compiled code (with Java 1.3 source/target compliance) on a Java 1.3 JVM?

I know this is quite odd, but most of our customers are on Java 5 but we are restricted by a few still on Java 1.3 due to conditions beyond our control.  Our CI tool uses Java 5 compiler but we set our source and target compliance to Java 1.3 for backward compatibility.  We are not using Java 1.3 for CI because there are unit tests that does not compile on 1.3.

Will this be an issue?

Thank you in advance!

Cheers,
- Paul

答: The biggest problem you will have is that while the JVM generated byte code will be compliant with 1.3, the JDK you're compiling against is Java 5. It is very easy to use a class, or more likely, a method that exists in Java 5, but not in the 1.3 JDK. This code will compile fine but will fail to run on a 1.3 runtime.</p>


问:
Sending Templated emails with node.js, node mailer and nodemailer-mailgun-transport
I have the following basic nodejs app:

```<code>var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
var options = {
 viewEngine: {
     extname: '.hbs',
     layoutsDir: 'views/email/',
     defaultLayout : 'template',
     partialsDir : 'views/partials/'
 },
 viewPath: 'views/email/',
 extName: '.hbs'
};

var mg = require('nodemailer-mailgun-transport');

var auth = {
    auth: {
        api_key: ' mailgun api key ',
        domain: ' mailgun email domain '
    }
}

var mailer = nodemailer.createTransport(mg(auth));

mailer.use('compile', hbs(options));
mailer.sendMail({
 from: 'test@inventori.io',
 to: 'test@test.com',
 subject: 'Any Subject',
 template: 'email.body',
 context: {
      variable1 : 'value1',
      variable2 : 'value2'
 }
}, function (error, response) {
    // console.error(error);
    if (error) {
        throw error;
    };
 console.log('mail sent to ',response);
 mailer.close();
});
</code>```

views/email/template.hbs

```<code>{{>email/head}}
<body>
     {{>email/header}}
     {{{body}}}
     {{>email/footer}}
</body>
</html>
</code>```

views/email/email.body.hbs

```<code><h4>Main Body Here</h4>
{{variable1}} <br/>
{{variable2}}
</code>```

views/partials/email/header.hbs

```<code><h4>Header Content</h4>
</code>```

views/partials/email/footer.hbs

```<code><h4>Footer Content</h4>
</code>```

The handlebars template engine gives zero errors but the mailgun transport throws the following error:

```<code>Error: Sorry: template parameter is not supported yet. Check back soon!
    at IncomingMessage.<anonymous> (~/test/node_modules/nodemailer-mailgun-transport/node_modules/mailgun-js/lib/request.js:228:15)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
</code>```

This example uses the gmail node mailer transport:

```<code>http://excellencenodejsblog.com/express-nodemailer-sending-mails/
</code>```

I would like to be able to send templated emails using mailgun.

Any help would be greatly appreciated.

Thank you.

答:
For me, templates weren't rendering properly because I was following an example using extName when the key was actually extname (all lowercase). Perhaps it was renamed overtime and the guide I was looking at is now somewhat out of date.

Full working example below as of 30 May 2020.

Directory Structure:

```<code>root/
   src/
      email-templates/
              layouts/
                     blank.hbs
              partials/
              hello.hbs
      services/
              email.service.ts
</code>```

email.service.ts (Haven't updated this to use proper types yet. Just a poc.)

export async function sendTestEmail() {
  try {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    const testAccount = await nodemailer.createTestAccount()

    // create reusable transporter object using the default SMTP transport
    const transporter = nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: testAccount.user, // generated ethereal user
        pass: testAccount.pass, // generated ethereal password
      },
    })

    transporter.use('compile', hbs({
      viewEngine: {
        extname: '.hbs', // handlebars extension
        partialsDir: 'src/email-templates',
        layoutsDir: 'src/email-templates/layouts',
        defaultLayout: 'blank',
      },
      viewPath: 'src/email-templates',
      extName: '.hbs'
    }))

    // send mail with defined transport object
    const mailOptions = {
      from: 'test@gmail.com', // sender address
      to: 'test@gmail.com', // list of receivers
      subject: 'Hello ✔', // Subject line
      text: 'Hello world?', // plain text body
      template: 'hello',
      context: {
        firstName: 'Clem'
      }
    }
    const info = await transporter.sendMail(mailOptions)

    console.log('Message sent: %s', info.messageId)
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
  } catch (error) {
    console.log(error)
  }
}
```

Body:
I have the following basic nodejs app:

var nodemailer = require('nodemailer');
var hbs = require('nodemailer-express-handlebars');
var options = {
 viewEngine: {
     extname: '.hbs',
     layoutsDir: 'views/email/',
     defaultLayout : 'template',
     partialsDir : 'views/partials/'
 },
 viewPath: 'views/email/',
 extName: '.hbs'
};

var mg = require('nodemailer-mailgun-transport');

var auth = {
    auth: {
        api_key: ' mailgun api key ',
        domain: ' mailgun email domain '
    }
}

var mailer = nodemailer.createTransport(mg(auth));

mailer.use('compile', hbs(options));
mailer.sendMail({
 from: 'test@inventori.io',
 to: 'test@test.com',
 subject: 'Any Subject',
 template: 'email.body',
 context: {
      variable1 : 'value1',
      variable2 : 'value2'
 }
}, function (error, response) {
    // console.error(error);
    if (error) {
        throw error;
    };
 console.log('mail sent to ',response);
 mailer.close();
});

views/email/template.hbs

{{>email/head}}

     {{>email/header}}
     {{{body}}}
     {{>email/footer}}

views/email/email.body.hbs

Main Body Here

{{variable1}}

{{variable2}}

views/partials/email/header.hbs

Header Content

views/partials/email/footer.hbs

Footer Content

The handlebars template engine gives zero errors but the mailgun transport throws the following error:

Error: Sorry: template parameter is not supported yet. Check back soon!
    at IncomingMessage.<anonymous> (~/test/node_modules/nodemailer-mailgun-transport/node_modules/mailgun-js/lib/request.js:228:15)
at IncomingMessage.emit (events.js:129:20)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)

This example uses the gmail node mailer transport:

http://excellencenodejsblog.com/express-nodemailer-sending-mails/

I would like to be able to send templated emails using mailgun.

Any help would be greatly appreciated.

Thank you.

Body:
For me, templates weren't rendering properly because I was following an example using extName when the key was actually extname (all lowercase). Perhaps it was renamed overtime and the guide I was looking at is now somewhat out of date.

Full working example below as of 30 May 2020.

Directory Structure:

root/
   src/
      email-templates/
              layouts/
                     blank.hbs
              partials/
              hello.hbs
      services/
              email.service.ts

email.service.ts (Haven't updated this to use proper types yet. Just a poc.)

export async function sendTestEmail() {
  try {
    // Generate test SMTP service account from ethereal.email
    // Only needed if you don't have a real mail account for testing
    const testAccount = await nodemailer.createTestAccount()

    // create reusable transporter object using the default SMTP transport
    const transporter = nodemailer.createTransport({
      host: 'smtp.ethereal.email',
      port: 587,
      secure: false, // true for 465, false for other ports
      auth: {
        user: testAccount.user, // generated ethereal user
        pass: testAccount.pass, // generated ethereal password
      },
    })

    transporter.use('compile', hbs({
      viewEngine: {
        extname: '.hbs', // handlebars extension
        partialsDir: 'src/email-templates',
        layoutsDir: 'src/email-templates/layouts',
        defaultLayout: 'blank',
      },
      viewPath: 'src/email-templates',
      extName: '.hbs'
    }))

    // send mail with defined transport object
    const mailOptions = {
      from: 'test@gmail.com', // sender address
      to: 'test@gmail.com', // list of receivers
      subject: 'Hello ✔', // Subject line
      text: 'Hello world?', // plain text body
      template: 'hello',
      context: {
        firstName: 'Clem'
      }
    }
    const info = await transporter.sendMail(mailOptions)

    console.log('Message sent: %s', info.messageId)
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

    // Preview only available when sending through an Ethereal account
    console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info))
    // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou...
  } catch (error) {
    console.log(error)
  }
}


问:
Inheritance problem in a Java/CXF/SOAP app?
I'm working on an application that uses cxf, the base of the app is a wsdl file and I'm having some trouble working with the inheritance.

I'll try to make a clear example (not exactly what I'm working on, but it should sum up the idea).
In the type definition I have the following

```<code><xsd:complexType name="Parent" abstract="true">
</xsd:complexType>
<xsd:complexType name="ChildA">
    <xsd:complexContent>
        <xsd:extension base="tns:Parent">
            <xsd:sequence>
                <xsd:element name="attr1" type="xsd:double"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="ChildB">
    <xsd:complexContent>
        <xsd:extension base="tns:Parent">
            <xsd:sequence>
                <xsd:element name="attr2" type="xsd:double"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>
</code>```

When the java code is generated using wsdl2java, everything works fine, I can even see the extends on the generated Child(A|B) classes.

However, if I implement a method that takes, as an input parameter, an element of the Parent type

```<code><xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:element name="input" type="tns:Parent"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</code>```

when I invoke the method from the client side (using the javascript generated by cxf) with the following (RemoteControl is the object handling the SOAP exchange in the client side) call:

```<code>var childA=new __childA();
childA.setAttr1(100);
RemoteControl.method(childA);
</code>```

On the java side I have the following error (the ... are there to replace the exact lines that are all linked to either to cxf or to sun.xml):

```<code>org.apache.cxf.interceptor.Fault: Unmarshalling Error: Unable to create an instance of Parent
...
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]]
...
Caused by: javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]
...
Caused by: javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]
...
Caused by: java.lang.InstantiationException
...
</code>```

However, if the declaration of the input parameter is

```<code><xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:element name="input" type="tns:childA"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</code>```

Everything is working fine.

So I'm wondering if it's possible to uses the Parent class as an input parameter. And if it is possible, what I'm missing in order to make that work.

Thanks.

Edit:

I didn't manage to get that working exactly like I wanted to, but I figured a way around.
I just used some other options of the xml schema. Two of those seems to work depending of the context.

First using choices (for a few childs):

```<code><xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:choice >
            <xsd:element name="inputA" type="tns:childA"/>
            <xsd:element name="inputB" type="tns:childB"/>
        </xsd:choice>
    </xsd:complexType>
</xsd:element>
</code>```

Secondly using any element (when there are numerous choices)

```<code><xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:any/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>
</code>```

But this one seems to ask for a little bit more of code on the server end.

P.S: <xsd:element name="methodInput" type="anyType" /> seems to produce an erroneous message on the client side, that's why I used a sequence.

答:
I don't think the javascript clients support type inheritance at all.   There are a bunch of restrictions on it.   Patches would be welcome.  :-)

In particular, the javascript would need to be updated to output an xsi:type="ns:Child1" attribute so JAXB can properly map it.

Body:
I'm working on an application that uses cxf, the base of the app is a wsdl file and I'm having some trouble working with the inheritance.

I'll try to make a clear example (not exactly what I'm working on, but it should sum up the idea).
In the type definition I have the following

<xsd:complexType name="Parent" abstract="true">
</xsd:complexType>
<xsd:complexType name="ChildA">
    <xsd:complexContent>
        <xsd:extension base="tns:Parent">
            <xsd:sequence>
                <xsd:element name="attr1" type="xsd:double"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>
<xsd:complexType name="ChildB">
    <xsd:complexContent>
        <xsd:extension base="tns:Parent">
            <xsd:sequence>
                <xsd:element name="attr2" type="xsd:double"/>
            </xsd:sequence>
        </xsd:extension>
    </xsd:complexContent>
</xsd:complexType>

When the java code is generated using wsdl2java, everything works fine, I can even see the extends on the generated Child(A|B) classes.

However, if I implement a method that takes, as an input parameter, an element of the Parent type

<xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:element name="input" type="tns:Parent"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

when I invoke the method from the client side (using the javascript generated by cxf) with the following (RemoteControl is the object handling the SOAP exchange in the client side) call:

var childA=new __childA();
childA.setAttr1(100);
RemoteControl.method(childA);

On the java side I have the following error (the ... are there to replace the exact lines that are all linked to either to cxf or to sun.xml):

org.apache.cxf.interceptor.Fault: Unmarshalling Error: Unable to create an instance of Parent
...
Caused by: javax.xml.bind.UnmarshalException
 - with linked exception:
[javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]]
...
Caused by: javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]
...
Caused by: javax.xml.bind.UnmarshalException: Unable to create an instance of Parent
 - with linked exception:
[java.lang.InstantiationException]
...
Caused by: java.lang.InstantiationException
...

However, if the declaration of the input parameter is

<xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:element name="input" type="tns:childA"/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

Everything is working fine.

So I'm wondering if it's possible to uses the Parent class as an input parameter. And if it is possible, what I'm missing in order to make that work.

Thanks.

Edit:

I didn't manage to get that working exactly like I wanted to, but I figured a way around.
I just used some other options of the xml schema. Two of those seems to work depending of the context.

First using choices (for a few childs):

<xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:choice >
            <xsd:element name="inputA" type="tns:childA"/>
            <xsd:element name="inputB" type="tns:childB"/>
        </xsd:choice>
    </xsd:complexType>
</xsd:element>

Secondly using any element (when there are numerous choices)

<xsd:element name="methodInput">
    <xsd:complexType>
        <xsd:sequence >
            <xsd:any/>
        </xsd:sequence>
    </xsd:complexType>
</xsd:element>

But this one seems to ask for a little bit more of code on the server end.

P.S: <xsd:element name="methodInput" type="anyType" /> seems to produce an erroneous message on the client side, that's why I used a sequence.


问:
how to compare checkbox checked string value with li element to edit last one
How can I compare checkbox checked string value with li element to edit last one.
For example.

```<code> jQuery(function($){

// start ajax
    $('#filter input[type="checkbox"]').on('change', function(){
        var filter = $('#filter');

                        /* Stuff to do every *odd* time the element is clicked */
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(), // form data
            type:filter.attr('method'), // POST
            beforeSend:function(xhr){
                filter.find('button').css('opacity', '1').text('Загрузка...');
                // changing the button label
            },
            success:function(data){
                filter.find('button').css('opacity', '0');; // changing the button label back
                if($(".checkbox:checked").length == 0) {
                                $('#response').empty();
                          } else {
                                $('#response').html(data);

                                 };

                                 $(".usage-product-list li").each(function () {
                                        if ($(this).text() == 'Усиление иммунитета') {
                                            $(this).css('color', 'red');
                                        }
                                    });

                                }
                    });
        return false;
                    });
//end jquery ajax

    // load more toggle start
    $('.load-more').toggle(function() {
    $(this).html('Меньше параметров <i class="fas fa-angle-up"></i>');
    $('.row-wrap').slideDown('slow');
}, function() {
    $(this).html('Больше параметров <i class="fas fa-angle-down"></i>');
    $('.row-wrap').slideUp('slow');
});
    // load more toggle end

    $('#filter input[type="checkbox"]').click(function () {
            $(this).siblings('span').toggleClass('active');
        });
    // end of stack
    });
// end of stack
</code>```

In my code I have to change the color of li if it contains a text which I put into the string, but how to change every li color with text string equal to each checked checkbox parent LABEL string value?

```<code> $(".usage-product-list li").each(function () {
                                            if ($(this).text() == 'Усиление иммунитета') {
                                                $(this).css('color', 'red');
                                            }
                                        });
</code>```

```<code>  <label><span></span><input class="checkbox" type="checkbox" name="usage_uluchpoedaemost"/>Улучшение поедаемости</label>
                    <label><span></span><input class="checkbox" type="checkbox" name="usage_usilimmun"/>Усиление иммунитета</label>
</code>```

答:
Just add this to your success function instead of the $(".usage-product-list li").each(function () {}); :

```<code>let checked = $("input[type='checkbox']:checked")
checked.each(function() {
   let labelText = $(this).closest("label").text();
    $(".usage-product-list li").each(function() {
       if ($(this).text() == labelText) {
          $(this).css('color', 'red');
       }
    });
});
</code>```

Body:
How can I compare checkbox checked string value with li element to edit last one.
For example.

 jQuery(function($){

// start ajax
    $('#filter input[type="checkbox"]').on('change', function(){
        var filter = $('#filter');

                        /* Stuff to do every *odd* time the element is clicked */
        $.ajax({
            url:filter.attr('action'),
            data:filter.serialize(), // form data
            type:filter.attr('method'), // POST
            beforeSend:function(xhr){
                filter.find('button').css('opacity', '1').text('Загрузка...');
                // changing the button label
            },
            success:function(data){
                filter.find('button').css('opacity', '0');; // changing the button label back
                if($(".checkbox:checked").length == 0) {
                                $('#response').empty();
                          } else {
                                $('#response').html(data);

                                 };

                                 $(".usage-product-list li").each(function () {
                                        if ($(this).text() == 'Усиление иммунитета') {
                                            $(this).css('color', 'red');
                                        }
                                    });

                                }
                    });
        return false;
                    });
//end jquery ajax

    // load more toggle start
    $('.load-more').toggle(function() {
    $(this).html('Меньше параметров ');
    $('.row-wrap').slideDown('slow');
}, function() {
    $(this).html('Больше параметров ');
    $('.row-wrap').slideUp('slow');
});
    // load more toggle end

    $('#filter input[type="checkbox"]').click(function () {
            $(this).siblings('span').toggleClass('active');
        });
    // end of stack
    });
// end of stack

In my code I have to change the color of li if it contains a text which I put into the string, but how to change every li color with text string equal to each checked checkbox parent LABEL string value?

 $(".usage-product-list li").each(function () {
                                            if ($(this).text() == 'Усиление иммунитета') {
                                                $(this).css('color', 'red');
                                            }
                                        });

  <input class="checkbox" type="checkbox" name="usage_uluchpoedaemost"/>Улучшение поедаемости
                    <input class="checkbox" type="checkbox" name="usage_usilimmun"/>Усиление иммунитета

Body:
Just add this to your success function instead of the $(".usage-product-list li").each(function () {}); :

let checked = $("input[type='checkbox']:checked")
checked.each(function() {
   let labelText = $(this).closest("label").text();
    $(".usage-product-list li").each(function() {
       if ($(this).text() == labelText) {
          $(this).css('color', 'red');
       }
    });
});