问:
Why does my BitSet have a size of 0?
Here is my code. What I am trying to do is process the bytes from my ByteBuffer using a BitSet. The ByteBuffer is loaded from DynamoDB(With the DynamoDBMapper)

```<code>    ByteBuffer buffer = .......
    System.out.println("Array length is " + buffer.array().length);
    BitSet bitSet = BitSet.valueOf(buffer.array());
    System.out.println("Bit set size is " + bitSet.size());
</code>```

When I execute my code, I see that the array length of my ByteBuffer is 6100, which means it's backed by 6100 bytes. These bytes are all 0s. However I also see that the bit set size is 0. This doesn't make sense to me.(The size should be 6100 * 8).

I looked at the documentation for valueOf and the description of "Returns a new bit set containing all the bits in the given byte array." makes sense for what I am trying to do.

The first mistake I made was to use the length of the bit set. The length is 0 which makes sense because all of the bits are 0s. The size function "returns the number of bits of space actually in use by this BitSet to represent bit values." Shouldn't the size function return 6100 * 8 here?

Update: I just tried putting all 1s into the bytebuffer and now am getting an array length of 7000 and a bit set size of 7232

答:
BitSet is not implemented to directly maintain a buffer equal in size to the array passed in to initialize it.  Instead, it internally maintains just enough buffer space to track the highest bit that is on.  For any bit higher than that, methods like BitSet#get assume that if passed a bit index higher than what is maintained in its current buffer space, the bit must be off.

There are several relevant statements in JavaDocs about the "size" or "length".  From the class-level JavaDocs of BitSet:

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length of a bit set and is defined independently of implementation.

From BitSet#length:

Returns the "logical size" of this BitSet: the index of the highest set bit in the BitSet plus one. Returns zero if the BitSet contains no set bits.

(Note also that in the extreme case of all bits off, it returns zero.)

From BitSet#size:

Returns the number of bits of space actually in use by this BitSet to represent bit values. The maximum element in the set is the size - 1st element.

If you're interested in a deeper dive, I also suggest looking at the OpenJDK code for BitSet:

http://hg.openjdk.java.net/jdk8u/jdk8u/jdk/file/3462d04401ba/src/share/classes/java/util/BitSet.java

Interesting parts are set, which dynamically expands buffer space as needed to set a particular bit on, and get, which is coded to return false if the requested bit index is beyond the current buffer capacity (the words member variable).

Title: Why does my BitSet have a size of 0?

Body:
Here is my code. What I am trying to do is process the bytes from my ByteBuffer using a BitSet. The ByteBuffer is loaded from DynamoDB(With the DynamoDBMapper)

    ByteBuffer buffer = .......
    System.out.println("Array length is " + buffer.array().length);
    BitSet bitSet = BitSet.valueOf(buffer.array());
    System.out.println("Bit set size is " + bitSet.size());

When I execute my code, I see that the array length of my ByteBuffer is 6100, which means it's backed by 6100 bytes. These bytes are all 0s. However I also see that the bit set size is 0. This doesn't make sense to me.(The size should be 6100 * 8).

I looked at the documentation for valueOf and the description of "Returns a new bit set containing all the bits in the given byte array." makes sense for what I am trying to do.

The first mistake I made was to use the length of the bit set. The length is 0 which makes sense because all of the bits are 0s. The size function "returns the number of bits of space actually in use by this BitSet to represent bit values." Shouldn't the size function return 6100 * 8 here?

Update: I just tried putting all 1s into the bytebuffer and now am getting an array length of 7000 and a bit set size of 7232


来源: stackexchange

问:
High-level level language for image processing
My final year project group is planning to build a real time application with neural network support and need to handle image processing efficiently, Any language suggestions would be very much helpful. Thanks.</p>

答:
How about Python? There is PIL, which

adds image processing capabilities to your Python interpreter. This library supports many file formats, and provides powerful image processing and graphics capabilities.

An introductory article about NN with python and a feed forward NN library:

http://www.ibm.com/developerworks/library/l-neurnet/

http://pypi.python.org/pypi/ffnet/0.6

ContentLicense: CC BY-SA 2.5


问:
handling json response data inside a list inside a dictionary python 3.6
i try to handle the odds from this betting site http://praktoreio.pamestoixima.gr/en/retail-football. With lots of help i pushed forward till the point i get some data

```<code>import requests
url = 'http://praktoreio.pamestoixima.gr/web/services/rs/
iFlexBetting/retail/games/15104/0.json?
shortTourn=true&startDrawNumber=686&endDrawNumber=686&sportId=s-
441&marketIds=0&marketIds=0A&marketIds=1&marketIds=69&marketIds=68&marketIds
=20&marketIds=21&marketIds=8&locale=en&brandId=defaultBrand&channelId=0'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
resp = requests.get(url, headers=headers)
html = resp.json()
data_1 = html[0]['markets'][0]['codes'][0]['oddPerSet']['1']
data_X = html[0]['markets'][0]['codes'][1]['oddPerSet']['1']
data_2 = html[0]['markets'][0]['codes'][2]['oddPerSet']['1']
print('odds for win:', data_1)
print('odds for draw:', data_X)
print('odds for lose:', data_2)
data_CODE_0 = html[0]['code']
print('Game code:', data_CODE_0)
</code>```

the thing is i get only those of element [0]. Instead of doing the above for every element is there a way to read float data inside a list inside a dictionary inside a list...automatically? Thanks in advance

答:
I'm not entirely sure what you're asking, but you can store a reference and then loop through it. I'm also assuming when you say element[0], you mean you want this behavior:

```<code>for element in html: # loops through list
    data = element['markets'][0]['codes']
        for x in data:
            print(x['oddPerSet']['1'])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
i try to handle the odds from this betting site http://praktoreio.pamestoixima.gr/en/retail-football. With lots of help i pushed forward till the point i get some data

import requests
url = 'http://praktoreio.pamestoixima.gr/web/services/rs/
iFlexBetting/retail/games/15104/0.json?
shortTourn=true&startDrawNumber=686&endDrawNumber=686&sportId=s-
441&marketIds=0&marketIds=0A&marketIds=1&marketIds=69&marketIds=68&marketIds
=20&marketIds=21&marketIds=8&locale=en&brandId=defaultBrand&channelId=0'
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'}
resp = requests.get(url, headers=headers)
html = resp.json()
data_1 = html[0]['markets'][0]['codes'][0]['oddPerSet']['1']
data_X = html[0]['markets'][0]['codes'][1]['oddPerSet']['1']
data_2 = html[0]['markets'][0]['codes'][2]['oddPerSet']['1']
print('odds for win:', data_1)
print('odds for draw:', data_X)
print('odds for lose:', data_2)
data_CODE_0 = html[0]['code']
print('Game code:', data_CODE_0)

the thing is i get only those of element [0]. Instead of doing the above for every element is there a way to read float data inside a list inside a dictionary inside a list...automatically? Thanks in advance

Body:
I'm not entirely sure what you're asking, but you can store a reference and then loop through it. I'm also assuming when you say element[0], you mean you want this behavior:

for element in html: # loops through list
    data = element['markets'][0]['codes']
        for x in data:
            print(x['oddPerSet']['1'])


问:
Oracle reclaim disk space after drop user cascade
I am using Oracle Database 12c. I had a big schema which was taking more than 20GB of my disk space. So I dropped it using the command:

```<code> drop user myDB cascade;
</code>```

However, the tablespace files continue to take space from the disk. In the image bellow taken from EM Express, we can see it has a lot of free space in between the data I still need.

My question is: how do I reorganize my tablespace to be in just one file and then have it resized so that I can have some more space in Disk?

Thanks in advance.

答:
This can be done by first creating a new tablespace with 1 datafile and then moving all segments from old tablespace to new tablespace, after all data is moved you can drop the old tablespace and rename new to old. In this way the new tablespace is compact and you free up unused disk space so that is available to the OS.

Sequence of steps :

create new tablespace TBS_B with 1 datafile

find out all the segments that need to be transferred from TBS_A to TBS_B     using"dba_segments" view

transfer table segments via "alter table ... move tablespace" command

transfer index segments via "alter index ... rebuild tablespace" command

Drop old tablepsace TBS_A

Rename new tablespace TBS_B to TBS_A

Body:
I am using Oracle Database 12c. I had a big schema which was taking more than 20GB of my disk space. So I dropped it using the command:

 drop user myDB cascade;

However, the tablespace files continue to take space from the disk. In the image bellow taken from EM Express, we can see it has a lot of free space in between the data I still need.

My question is: how do I reorganize my tablespace to be in just one file and then have it resized so that I can have some more space in Disk?

Thanks in advance.


问:
How to setup a Pub/Sub in nanomsg between a C and Python sides?
I'm trying to learn the nanomsg library.

I'm using the code examples of both versions C and Python. I'm trying to subscribe to the C service with a Python script, but nothing is happening.

Here's both of my code :

Python subscriber

```<code>from __future__ import print_function
from nanomsg import Socket, PAIR, PUB
s2 = Socket(PAIR)
while(True):
    s2.connect('tcp://127.0.0.1:5555')
    s2.send(b'hello nanomsg #1')
    s2.send(b'hello nanomsg #2')
    s2.close()
</code>```

C code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>  /* For htonl and ntohl */
#include <unistd.h>

#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>

/*  The server runs forever. */
int server(const char *url)
{
    int fd;

    /*  Create the socket. */
    fd = nn_socket (AF_SP, NN_PUB);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    /*  Bind to the URL.  This will bind to the address and listen
        synchronously; new clients will be accepted asynchronously
        without further action from the calling program. */

    if (nn_bind (fd, url) < 0) {
        fprintf (stderr, "nn_bind: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    /*  Now we can just publish results.  Note that there is no explicit
        accept required.  We just start writing the information. */

    for (;;) {
        uint8_t msg[2 * sizeof (uint32_t)];
        uint32_t secs, subs;
        int rc;

        secs = (uint32_t) time (NULL);
        subs = (uint32_t) nn_get_statistic (fd, NN_STAT_CURRENT_CONNECTIONS);

        secs = htonl (secs);
        subs = htonl (subs);

        memcpy (msg, &secs, sizeof (secs));
        memcpy (msg + sizeof (secs), &subs, sizeof (subs));

        rc = nn_send (fd, msg, sizeof (msg), 0);
        if (rc < 0) {
            /*  There are several legitimate reasons this can fail.
                We note them for debugging purposes, but then ignore
                otherwise. */
            fprintf (stderr, "nn_send: %s (ignoring)\n",
                nn_strerror (nn_errno ()));
        }
        sleep(10);
    }

    /* NOTREACHED */
    nn_close (fd);
    return (-1);
}

/*  The client runs in a loop, displaying the content. */
int client (const char *url)
{
    int fd;
    int rc;

    fd = nn_socket (AF_SP, NN_SUB);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    if (nn_connect (fd, url) < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    /*  We want all messages, so just subscribe to the empty value. */
    if (nn_setsockopt (fd, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) < 0) {
        fprintf (stderr, "nn_setsockopt: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    for (;;) {
        uint8_t msg[2 * sizeof (uint32_t)];
        char hhmmss[9];  /* HH:MM:SS\0 */
        uint32_t subs, secs;
        time_t t;

        rc = nn_recv (fd, msg, sizeof (msg), 0);
        if (rc < 0) {
            fprintf (stderr, "nn_recv: %s\n", nn_strerror (nn_errno ()));
            break;
        }
        if (rc != sizeof (msg)) {
            fprintf (stderr, "nn_recv: got %d bytes, wanted %d\n",
                rc, (int)sizeof (msg));
             break;
        }
        memcpy (&secs, msg, sizeof (secs));
        memcpy (&subs, msg + sizeof (secs), sizeof (subs));

        t = (time_t) ntohl(secs);
        strftime (hhmmss, sizeof (hhmmss), "%T", localtime (&t));

        printf ("%s <pid %u> There are %u clients connected.\n", hhmmss,
            (unsigned) getpid(), (unsigned) ntohl(subs));
    }

    nn_close (fd);
    return (-1);
}

int main (int argc, char **argv)
{
    int rc;
    if ((argc == 3) && (strcmp (argv[2], "-s") == 0)) {
        rc = server (argv[1]);
    } else if (argc == 2) {
        rc = client (argv[1]);
    } else {
        fprintf (stderr, "Usage: %s <url> [-s]\n", argv[0]);
        exit (EXIT_FAILURE);
    }
    exit (rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
</code>```

I run the C code by doing

./pubsub_demo tcp://127.0.0.1:5555 -s

Thanks for your help

答:
The C code looks good. It comes from here.

A simpler version of C NN_PUB server and NN_SUB client also exists.

There are a few problems with presented the Python code.

1) In nanomsg we have to match behavioural-"protocols". In order to receive a NN_PUB broadcast from the C server, we have to have a matching SUB, not a PAIR, socket on the Python side.

2) Connect to the same endpoint-transport-class://address:port as NN_PUB socket nn_bind()-s to. There is no need to do it in the loop.

3) The socket has to have SUB_SUBSCRIBE option set.

4) SUB socket is for listening, it is not designed to .send() anything.

An untested Python program may look in-principle as follows:

```<code># import appropriate modules for the nanomsg socket
from nanomsg import Socket, PUB, SUB, SUB_SUBSCRIBE

# open Python's SUB socket matching the NN_PUB socket on the C side
s2 = Socket(SUB)
# s2 should be >= 0

# connect the socket to the same endpoint as NN_PUB server
ret1 = s2.connect('tcp://127.0.0.1:5555')
# ret1 should be 0

# subscribe to everything:
ret2 = s2.set_string_option(SUB, SUB_SUBSCRIBE, '')
# ret1 should be 0

# receive messages:
while(True):
    message = s2.recv()
</code>```

You can also look at Python test PUB/SUB example

I hope it helps.

Body:
I'm trying to learn the nanomsg library.

I'm using the code examples of both versions C and Python. I'm trying to subscribe to the C service with a Python script, but nothing is happening.

Here's both of my code :

Python subscriber

from __future__ import print_function
from nanomsg import Socket, PAIR, PUB
s2 = Socket(PAIR)
while(True):
    s2.connect('tcp://127.0.0.1:5555')
    s2.send(b'hello nanomsg #1')
    s2.send(b'hello nanomsg #2')
    s2.close()

C code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <netinet/in.h>  /* For htonl and ntohl */
#include <unistd.h>

#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>

/*  The server runs forever. */
int server(const char *url)
{
    int fd;

    /*  Create the socket. */
    fd = nn_socket (AF_SP, NN_PUB);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    /*  Bind to the URL.  This will bind to the address and listen
        synchronously; new clients will be accepted asynchronously
        without further action from the calling program. */

    if (nn_bind (fd, url) < 0) {
        fprintf (stderr, "nn_bind: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    /*  Now we can just publish results.  Note that there is no explicit
        accept required.  We just start writing the information. */

    for (;;) {
        uint8_t msg[2 * sizeof (uint32_t)];
        uint32_t secs, subs;
        int rc;

        secs = (uint32_t) time (NULL);
        subs = (uint32_t) nn_get_statistic (fd, NN_STAT_CURRENT_CONNECTIONS);

        secs = htonl (secs);
        subs = htonl (subs);

        memcpy (msg, &secs, sizeof (secs));
        memcpy (msg + sizeof (secs), &subs, sizeof (subs));

        rc = nn_send (fd, msg, sizeof (msg), 0);
        if (rc < 0) {
            /*  There are several legitimate reasons this can fail.
                We note them for debugging purposes, but then ignore
                otherwise. */
            fprintf (stderr, "nn_send: %s (ignoring)\n",
                nn_strerror (nn_errno ()));
        }
        sleep(10);
    }

    /* NOTREACHED */
    nn_close (fd);
    return (-1);
}

/*  The client runs in a loop, displaying the content. */
int client (const char *url)
{
    int fd;
    int rc;

    fd = nn_socket (AF_SP, NN_SUB);
    if (fd < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        return (-1);
    }

    if (nn_connect (fd, url) < 0) {
        fprintf (stderr, "nn_socket: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    /*  We want all messages, so just subscribe to the empty value. */
    if (nn_setsockopt (fd, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) < 0) {
        fprintf (stderr, "nn_setsockopt: %s\n", nn_strerror (nn_errno ()));
        nn_close (fd);
        return (-1);
    }

    for (;;) {
        uint8_t msg[2 * sizeof (uint32_t)];
        char hhmmss[9];  /* HH:MM:SS\0 */
        uint32_t subs, secs;
        time_t t;

        rc = nn_recv (fd, msg, sizeof (msg), 0);
        if (rc < 0) {
            fprintf (stderr, "nn_recv: %s\n", nn_strerror (nn_errno ()));
            break;
        }
        if (rc != sizeof (msg)) {
            fprintf (stderr, "nn_recv: got %d bytes, wanted %d\n",
                rc, (int)sizeof (msg));
             break;
        }
        memcpy (&secs, msg, sizeof (secs));
        memcpy (&subs, msg + sizeof (secs), sizeof (subs));

        t = (time_t) ntohl(secs);
        strftime (hhmmss, sizeof (hhmmss), "%T", localtime (&t));

        printf ("%s <pid %u> There are %u clients connected.\n", hhmmss,
            (unsigned) getpid(), (unsigned) ntohl(subs));
    }

    nn_close (fd);
    return (-1);
}

int main (int argc, char **argv)
{
    int rc;
    if ((argc == 3) && (strcmp (argv[2], "-s") == 0)) {
        rc = server (argv[1]);
    } else if (argc == 2) {
        rc = client (argv[1]);
    } else {
        fprintf (stderr, "Usage: %s <url> [-s]\n", argv[0]);
        exit (EXIT_FAILURE);
    }
    exit (rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}

I run the C code by doing

./pubsub_demo tcp://127.0.0.1:5555 -s

Thanks for your help

Body:
The C code looks good. It comes from here.

A simpler version of C NN_PUB server and NN_SUB client also exists.

There are a few problems with presented the Python code.

1) In nanomsg we have to match behavioural-"protocols". In order to receive a NN_PUB broadcast from the C server, we have to have a matching SUB, not a PAIR, socket on the Python side.

2) Connect to the same endpoint-transport-class://address:port as NN_PUB socket nn_bind()-s to. There is no need to do it in the loop.

3) The socket has to have SUB_SUBSCRIBE option set.

4) SUB socket is for listening, it is not designed to .send() anything.

An untested Python program may look in-principle as follows:

# import appropriate modules for the nanomsg socket
from nanomsg import Socket, PUB, SUB, SUB_SUBSCRIBE

# open Python's SUB socket matching the NN_PUB socket on the C side
s2 = Socket(SUB)
# s2 should be >= 0

# connect the socket to the same endpoint as NN_PUB server
ret1 = s2.connect('tcp://127.0.0.1:5555')
# ret1 should be 0

# subscribe to everything:
ret2 = s2.set_string_option(SUB, SUB_SUBSCRIBE, '')
# ret1 should be 0

# receive messages:
while(True):
    message = s2.recv()

You can also look at Python test PUB/SUB example

I hope it helps.


问:
Best way to perform mutually exclusive selection in a tableview in different sections in swift 3
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

```<code>   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }
</code>```

答:
You should create some data element to track the selection for each row.

I would suggest a dictionary of [Int:Int] where the key is the section and the value is the row.

When a row is selected, you can then easily check to see if another row is already selected in that section, and deselect it if required.

```<code>var rowSelections = [Int:Int]()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        if let row = self.rowSelections[section] {
            tableView.deselectRow(at: IndexPath(row:row, section:section), animated: true)
        }
        self.rowSelections[section]=indexPath.row
    }

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let section = indexPath.section
    self.rowSelections[section]=nil
}
</code>```

Body:
I have a tableview with different sections, I need to be able to multiselect from different sections, but the rows in each section should be able to select mutually exclusive wise. For eg: in below screenshot I should be able to select either Margarita or BBQ Chicken from Pizza and same for Deep dish pizza but I should be able to multiselect between Pizza section and Deep dish pizza

Below is my code so far, I was wondering what would be the best way to approach this.

   let section = ["Pizza", "Deep dish pizza"]

    let items = [["Margarita", "BBQ Chicken"], ["Sausage", "meat lovers"]]

override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.section[section]
    }

    override func numberOfSections(in tableView: UITableView) -> Int {

        return section.count
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return items[section].count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)

        // Configure the cell...

        cell.textLabel?.text = items[indexPath.section][indexPath.row]

        return cell
    }

Body:
You should create some data element to track the selection for each row.

I would suggest a dictionary of [Int:Int] where the key is the section and the value is the row.

When a row is selected, you can then easily check to see if another row is already selected in that section, and deselect it if required.

var rowSelections = [Int:Int]()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let section = indexPath.section
        if let row = self.rowSelections[section] {
            tableView.deselectRow(at: IndexPath(row:row, section:section), animated: true)
        }
        self.rowSelections[section]=indexPath.row
    }

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let section = indexPath.section
    self.rowSelections[section]=nil
}


问:
How do you handle versioning of Spotfire dashboards?
Natural thing about software is that you enhance it, thus you create next versions of it. How do you handle that in concern of Spotfire ?</p>

答:
At least two ways I can think of.

First, in 7.5 and above you can spin up a test node and copy down any dxp you want from live to develop in test. Once the "upgrade" or changes are complete you then would backup the live version to disk somewhere... anywhere you do other backups, and deploy the new version to live.

For pre-7.5 the idea is the same but you would have to create a test folder in live with restricted access to test your upgrade on a web player.

Strictly speaking of "what version are you on" in regards to Analytics like there is in software isn't really the same in my opinion. There should only be one version of the truth. If you are to run multiple versions you'd have to manage their updates separately for caching which is cumbersome in my opinion. Also, realizing the analytic has a GUID which relates to its information sources means that running them in parallel in the same environment will cause duplication.

If this isn't what you were shooting for I'd love for you to elaborate on the original post and clarify anything I assumed. Cheers mate.

EDIT

Regarding the changes in 7.5, see this article from Tibco starting on p.42 which explains that Spotfire has a new topology with a service oriented architecture. In 7.5 onward, IIS is no longer used and to access the web player you doesn't even go to the "web server" anymore. The application server handles all access and is the central point for authentication and management.


问:
Build custom Metric for Loss Function with Keras, with errors
I'm trying to write custom metric function to set in the compile step wrote in this way:

```<code>self.model.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=[self.dice_similarity_coefficient_metric,self.positive_predictive_value_metric,self.sensitivity_metric])
</code>```

I wrote Dice Similarity Coefficient, Positive Predictive Value and Similarity in this way:

FP = false positive

TP = true positive

FN = false negative

```<code> def dice_similarity_coefficient_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) &
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array((2 * TP) / (FP + (2 * TP) + FN +
        K.epsilon())))
</code>```

```<code>    def positive_predictive_value_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        return K.variable(np.array(TP / (FP + TP + K.epsilon())))
</code>```

```<code>    def sensitivity_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) &
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array(TP / (TP + FN + K.epsilon())))
</code>```

when i run the code i have the following error:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'dense_3_target' with dtype float
       [[Node: dense_3_target = Placeholderdtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Can someone care to explain where is the problem?
Where i'm wrong?

Thank you

答:
Probably, it's better to define metrics using backend functions. For example:

```<code>def false_negatives(Y_true, Y_pred):
    return K.sum(K.round(K.clip(Y_true - Y_pred, 0, 1)))
</code>```

It can be checked on an example data with 5 FN:

```<code>y_true = np.array([[1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], dtype=np.float32)
y_pred = np.array([[0.3, 0.99, 0.99, 0.1], [0.6, 0.99, 0.99, 0.1], [0.1, 0.99, 0.99, 0.1]], dtype=np.float32)
n_fn = np.sum((y_true - y_pred) > 0.5)
Y_true = K.placeholder((None, 4), dtype=K.floatx())
Y_pred = K.placeholder((None, 4), dtype=K.floatx())
n_fn = false_negatives(Y_true, Y_pred).eval(inputs_to_values={Y_true: y_true, Y_pred: y_pred})
</code>```

HTH

Body:
I'm trying to write custom metric function to set in the compile step wrote in this way:

self.model.compile(optimizer=sgd,loss='categorical_crossentropy',metrics=[self.dice_similarity_coefficient_metric,self.positive_predictive_value_metric,self.sensitivity_metric])

I wrote Dice Similarity Coefficient, Positive Predictive Value and Similarity in this way:

FP = false positive

TP = true positive

FN = false negative

 def dice_similarity_coefficient_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) &
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array((2 * TP) / (FP + (2 * TP) + FN +
        K.epsilon())))

    def positive_predictive_value_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        FP = np.sum(y_pred & np.logical_not(y_true)).astype(float)
        TP = np.sum(y_true & y_pred).astype(float)
        return K.variable(np.array(TP / (FP + TP + K.epsilon())))

    def sensitivity_metric(self, y_true, y_pred):
        y_true = np.array(K.eval(y_true))
        y_pred = np.array(K.eval(y_pred))
        TP = np.sum(y_true & y_pred).astype(float)
        FN = np.sum(np.logical_not(y_pred) &
        np.logical_not(y_true)).astype(float)
        return K.variable(np.array(TP / (TP + FN + K.epsilon())))

when i run the code i have the following error:

InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'dense_3_target' with dtype float
       [[Node: dense_3_target = Placeholderdtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/cpu:0"]]

Can someone care to explain where is the problem?
Where i'm wrong?

Thank you

Body:
Probably, it's better to define metrics using backend functions. For example:

def false_negatives(Y_true, Y_pred):
    return K.sum(K.round(K.clip(Y_true - Y_pred, 0, 1)))

It can be checked on an example data with 5 FN:

y_true = np.array([[1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]], dtype=np.float32)
y_pred = np.array([[0.3, 0.99, 0.99, 0.1], [0.6, 0.99, 0.99, 0.1], [0.1, 0.99, 0.99, 0.1]], dtype=np.float32)
n_fn = np.sum((y_true - y_pred) > 0.5)
Y_true = K.placeholder((None, 4), dtype=K.floatx())
Y_pred = K.placeholder((None, 4), dtype=K.floatx())
n_fn = false_negatives(Y_true, Y_pred).eval(inputs_to_values={Y_true: y_true, Y_pred: y_pred})

HTH


问:
How to convert DNAbin to DNAStringSet?
I am trying to get an alignment in ape  from R with this code:

```<code>library(muscle)
#https://bioconductor.org/packages/release/bioc/html/muscle.html

muscle(x, exec = "muscle", MoreArgs = "", quiet = TRUE)
</code>```

but the console says:

```<code> Error in muscle(x, exec = "muscle", MoreArgs = "",  :
input must be an object of class XStringSet: DNAStringSet, RNAStringSet, or AAStringSet
</code>```

答:
You can convert any DNAbin to DNAStringSet by

```<code>library(magrittr)

yourDNAbin %>% as.character %>% lapply(.,paste0,collapse="") %>% unlist %>% DNAStringSet
</code>```

if your DNAbin is: xxx DNA sequences in binary format stored in a list.
If it is stored in a matrix as.list it first.

Title: How to convert DNAbin to DNAStringSet?

Body:
I am trying to get an alignment in ape  from R with this code:

library(muscle)
#https://bioconductor.org/packages/release/bioc/html/muscle.html

muscle(x, exec = "muscle", MoreArgs = "", quiet = TRUE)

but the console says:

 Error in muscle(x, exec = "muscle", MoreArgs = "",  :
input must be an object of class XStringSet: DNAStringSet, RNAStringSet, or AAStringSet

Body:
You can convert any DNAbin to DNAStringSet by

library(magrittr)

yourDNAbin %>% as.character %>% lapply(.,paste0,collapse="") %>% unlist %>% DNAStringSet

if your DNAbin is: xxx DNA sequences in binary format stored in a list.
If it is stored in a matrix as.list it first.


问:
ReactiveUI CancelableCommand with RestApi
I'm woring on MVVM application and trying to have a textbox text change register to run a command that can be canceled every time new change on this textbox happens.
In Reactive Extension it is done with a Switch method something like this:

```<code>Observable.FromEventPattern<PropertyChangedEventArgs>(this, nameof(PropertyChanged))
            .Where(a => a.EventArgs.PropertyName == nameof(Item))
            .Select(a => Item)
            .DistinctUntilChanged()
            .Throttle(TimeSpan.FromSeconds(0.5))
            .ObserveOn(SynchronizationContext.Current)
            .Do(x => { Items= null; })
            .ObserveOn(Scheduler.Default)
            .Select(item => { return Observable.FromAsync(cancellationToken => _itemService.GetItemsAsyncWithCancelation(item, cancellationToken)); })
            .Switch()
            .ObserveOn(SynchronizationContext.Current)
            .Subscribe(items => Items = items);
</code>```

When i try to do same thing with ReactiveUi this is what i have come up so far:

```<code>public ReactiveCommand GetItemsCommand { get; set; }
GetTowaryCommand = ReactiveCommand
       .CreateFromTask<string>(async (x,cancelationToken) => Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(),cancelationToken));

this.WhenAnyValue(vm => vm.Item)
       .Throttle(TimeSpan.FromSeconds(0.5))
       .Do(_=> GetTowaryCommand.Dispose())
       .ObserveOn(SynchronizationContext.Current)
       .InvokeCommand(GetItemsCommand);
</code>```

It is working but i'm not sure if the RestApi call is being canceled properly.
I was trying to follow example from ReactiveUI Documentation:
https://docs.reactiveui.net/en/user-guide/commands/canceling.html
but don't know how to pass string parameter (x) to restApi method:

```<code>GetItemsCommand
   .CreateFromObservable<string>(() => Observable.StartAsync(async (token) => Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)))
</code>```

答:
Since I don't exactly know what the concrete question here is, I'll just try and see what I can do here.

Change your GetItemsCommand to be of type ReactiveCommand<string, Unit> (string goes in, Unit goes out). Then you can say:

```<code>GetItemsCommand.CreateFromObservable<string,Unit>(x =>
    Observable.StartAsync(async (token) =>
        Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)))
</code>```

InvokeCommand will automatically pass in the parameter to the command if there's one available (i.e. Observable.Return("hello").InvokeCommand(GetItemsCommand) will pass "hello" to the command), so you would probably need to modify whatever code invokes GetItemsCommand.

As a side note, you can rewrite this in a slightly more clean separation-of-concerns kinda way by returning your list from the command and setting the Items property in the command's Subscribe block:

```<code>public ReactiveCommand<string, IEnumerable<T>> GetItemsCommand { get; set; }

GetItemsCommand.CreateFromObservable<string, IEnumerable<T>>(x =>
    Observable.FromAsync(token =>
        _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)));

// always runs on UI thread
GetItemsCommand.Subscribe(x => Items = x);
</code>```

Also, you generally shouldn't call ReactiveCommand.Dispose manually (the docs you linked call Dispose on the subscription, not on the command). Passing in a CancellationToken or setting up another observable to cancel the running command (both are in your link) is generally the cleanest way to achieve that.

For example:

```<code>var stream = this.WhenAnyValue(vm => vm.Item)
    .Throttle(TimeSpan.FromSeconds(0.5))
    .DistinctUntilChanged();

stream
    .InvokeCommand(GetItemsCommand);

GetItemsCommand.CreateFromObservable<string, IEnumerable<T>>(x =>
    Observable
        .FromAsync(token => _itemService.GetItemsAsyncWithCancelation(x.ToString(), token))
        .TakeUntil(stream));

GetItemsCommand.Subscribe(x => Items = x);
</code>```

Haven't actually tested this last bit, but I feel like it should work :) Just some ideas.

Body:
I'm woring on MVVM application and trying to have a textbox text change register to run a command that can be canceled every time new change on this textbox happens.
In Reactive Extension it is done with a Switch method something like this:

Observable.FromEventPattern<PropertyChangedEventArgs>(this, nameof(PropertyChanged))
            .Where(a => a.EventArgs.PropertyName == nameof(Item))
            .Select(a => Item)
            .DistinctUntilChanged()
            .Throttle(TimeSpan.FromSeconds(0.5))
            .ObserveOn(SynchronizationContext.Current)
            .Do(x => { Items= null; })
            .ObserveOn(Scheduler.Default)
            .Select(item => { return Observable.FromAsync(cancellationToken => _itemService.GetItemsAsyncWithCancelation(item, cancellationToken)); })
            .Switch()
            .ObserveOn(SynchronizationContext.Current)
            .Subscribe(items => Items = items);

When i try to do same thing with ReactiveUi this is what i have come up so far:

public ReactiveCommand GetItemsCommand { get; set; }
GetTowaryCommand = ReactiveCommand
       .CreateFromTask<string>(async (x,cancelationToken) => Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(),cancelationToken));

this.WhenAnyValue(vm => vm.Item)
       .Throttle(TimeSpan.FromSeconds(0.5))
       .Do(_=> GetTowaryCommand.Dispose())
       .ObserveOn(SynchronizationContext.Current)
       .InvokeCommand(GetItemsCommand);

It is working but i'm not sure if the RestApi call is being canceled properly.
I was trying to follow example from ReactiveUI Documentation:
https://docs.reactiveui.net/en/user-guide/commands/canceling.html
but don't know how to pass string parameter (x) to restApi method:

GetItemsCommand
   .CreateFromObservable<string>(() => Observable.StartAsync(async (token) => Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)))

Body:
Since I don't exactly know what the concrete question here is, I'll just try and see what I can do here.

Change your GetItemsCommand to be of type ReactiveCommand<string, Unit> (string goes in, Unit goes out). Then you can say:

GetItemsCommand.CreateFromObservable<string,Unit>(x =>
    Observable.StartAsync(async (token) =>
        Items = await _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)))

InvokeCommand will automatically pass in the parameter to the command if there's one available (i.e. Observable.Return("hello").InvokeCommand(GetItemsCommand) will pass "hello" to the command), so you would probably need to modify whatever code invokes GetItemsCommand.

As a side note, you can rewrite this in a slightly more clean separation-of-concerns kinda way by returning your list from the command and setting the Items property in the command's Subscribe block:

public ReactiveCommand<string, IEnumerable<T>> GetItemsCommand { get; set; }

GetItemsCommand.CreateFromObservable<string, IEnumerable<T>>(x =>
    Observable.FromAsync(token =>
        _itemService.GetItemsAsyncWithCancelation(x.ToString(), token)));

// always runs on UI thread
GetItemsCommand.Subscribe(x => Items = x);

Also, you generally shouldn't call ReactiveCommand.Dispose manually (the docs you linked call Dispose on the subscription, not on the command). Passing in a CancellationToken or setting up another observable to cancel the running command (both are in your link) is generally the cleanest way to achieve that.

For example:

var stream = this.WhenAnyValue(vm => vm.Item)
    .Throttle(TimeSpan.FromSeconds(0.5))
    .DistinctUntilChanged();

stream
    .InvokeCommand(GetItemsCommand);

GetItemsCommand.CreateFromObservable<string, IEnumerable<T>>(x =>
    Observable
        .FromAsync(token => _itemService.GetItemsAsyncWithCancelation(x.ToString(), token))
        .TakeUntil(stream));

GetItemsCommand.Subscribe(x => Items = x);

Haven't actually tested this last bit, but I feel like it should work :) Just some ideas.


答: Matlab provides a lot of features for image processing. May be slightly slow, but I assume performance is not an issue.</p>

Title: High-level level language for image processing

Body: My final year project group is planning to build a real time application with neural network support and need to handle image processing efficiently, Any language suggestions would be very much helpful. Thanks.


问:
Integer Array inside if/Elif Statement
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

```<code>for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)
</code>```

答:
Here's what I would do

```<code>some_num_dict = {
    '1': startw1,
    '2': startw2,
    '3': startw3,
    '4': startw4,
    '5': startw5,
    '6': startw6,
    '7': startw7,
    '8': startw8,
    '9': startw9
}
for number in f:
    some_num_dict[number[0]].append(number)
</code>```

Of course, I'm assuming number is some numerical string object.

EDIT: Just like how the others mention. If your just doing 9 lists that are similar to each other, it may be better to make a list of the lists...

Title: Integer Array inside if/Elif Statement

Body:
I currently have the following code, which appends lines of a text file to respective lists if they begin with a certain number.

Is there a way I can and use a numerical array and loop to save some lines of code? The number just needs to stop at 9.

Thank you.

for number in f:
if number.startswith('1'):
        startsw1.append(number)
elif number.startswith('2'):
        startsw2.append(number)
elif number.startswith('3'):
        startsw3.append(number)
elif number.startswith('4'):
        startsw4.append(number)
elif number.startswith('5'):
        startsw5.append(number)
elif number.startswith('6'):
    startsw6.append(number)
elif number.startswith('7'):
    startsw7.append(number)
elif number.startswith('8'):
        startsw8.append(number)
elif number.startswith('9'):
    startsw9.append(number)

Body:
Here's what I would do

some_num_dict = {
    '1': startw1,
    '2': startw2,
    '3': startw3,
    '4': startw4,
    '5': startw5,
    '6': startw6,
    '7': startw7,
    '8': startw8,
    '9': startw9
}
for number in f:
    some_num_dict[number[0]].append(number)

Of course, I'm assuming number is some numerical string object.

EDIT: Just like how the others mention. If your just doing 9 lists that are similar to each other, it may be better to make a list of the lists...


问:
Groovy script can't find JNA Class
I want to write event in Windows and only groovy is supported on my application.

I wrote short code to test, but I got the following exception always :

```<code>Java.lang.NoClassDefFoundError: Could not initialize class com.sun.jna.platform.win32.Advapi32
    at ProcessStateHandler.registerEventSource(test.groovy:32)
    at ProcessStateHandler.main(test.groovy:23)
</code>```

Test code is like this :

```<code>import com.sun.jna.platform.win32.Advapi32
import com.sun.jna.platform.win32.Advapi32Util
import com.sun.jna.platform.win32.Kernel32
import com.sun.jna.platform.win32.Win32Exception
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.platform.win32.WinNT.HANDLE
import com.sun.jna.platform.win32.WinReg

import com.sun.jna.Native
import com.sun.jna.Library
import com.sun.jna.Platform
import com.sun.jna.Pointer

public class ProcessStateHandler {
    def APPLICATION_EVENT_LOG_REGISTRY = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"
    public static void main(String[] args) {
        println "First groovy test"
        CLibrary.INSTANCE.printf("Hello, World\n")

        ProcessStateHandler processStateHandler = new ProcessStateHandler()
        processStateHandler.registerEventSource("", "SourceForTest")
    }

    private void registerEventSource(String server, String source) {

        source = source.trim()

        assert Advapi32
//        assert Advapi32.INSTANCE
        HANDLE eventHandle = Advapi32.INSTANCE.RegisterEventSource(server, source)
    }
}

public interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? 'msvcrt' : 'c'), CLibrary.class)

    void printf(String format, Object... args)
}
</code>```

In my guess, groovy does not support variables in Interface. Advapi32 interface is declared like this.

```<code>public interface Advapi32 extends StdCallLibrary {
    Advapi32 INSTANCE = (Advapi32) Native.loadLibrary("Advapi32",
            Advapi32.class, W32APIOptions.UNICODE_OPTIONS);
   /* blah
      blah
      blah */
}
</code>```

How do I access INSTANCE or call method in Advapi32 interface?

答:
Maybe, my test was wrong. </p>

<p>When i test the codes in Eclipse, there is no problem.
GroovyConsole may have class loader problem. </p>

Title: Groovy script can't find JNA Class

Body:
I want to write event in Windows and only groovy is supported on my application.

I wrote short code to test, but I got the following exception always :

Java.lang.NoClassDefFoundError: Could not initialize class com.sun.jna.platform.win32.Advapi32
    at ProcessStateHandler.registerEventSource(test.groovy:32)
    at ProcessStateHandler.main(test.groovy:23)

Test code is like this :

import com.sun.jna.platform.win32.Advapi32
import com.sun.jna.platform.win32.Advapi32Util
import com.sun.jna.platform.win32.Kernel32
import com.sun.jna.platform.win32.Win32Exception
import com.sun.jna.platform.win32.WinNT
import com.sun.jna.platform.win32.WinNT.HANDLE
import com.sun.jna.platform.win32.WinReg

import com.sun.jna.Native
import com.sun.jna.Library
import com.sun.jna.Platform
import com.sun.jna.Pointer

public class ProcessStateHandler {
    def APPLICATION_EVENT_LOG_REGISTRY = "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application"
    public static void main(String[] args) {
        println "First groovy test"
        CLibrary.INSTANCE.printf("Hello, World\n")

        ProcessStateHandler processStateHandler = new ProcessStateHandler()
        processStateHandler.registerEventSource("", "SourceForTest")
    }

    private void registerEventSource(String server, String source) {

        source = source.trim()

        assert Advapi32
//        assert Advapi32.INSTANCE
        HANDLE eventHandle = Advapi32.INSTANCE.RegisterEventSource(server, source)
    }
}

public interface CLibrary extends Library {
    CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? 'msvcrt' : 'c'), CLibrary.class)

    void printf(String format, Object... args)
}

In my guess, groovy does not support variables in Interface. Advapi32 interface is declared like this.

public interface Advapi32 extends StdCallLibrary {
    Advapi32 INSTANCE = (Advapi32) Native.loadLibrary("Advapi32",
            Advapi32.class, W32APIOptions.UNICODE_OPTIONS);
   /* blah
      blah
      blah */
}

How do I access INSTANCE or call method in Advapi32 interface?

Body:
Maybe, my test was wrong.

When i test the codes in Eclipse, there is no problem.
GroovyConsole may have class loader problem.


问:
How to stop only one app?
Jetty is running 3 sites from webapps. On of which is a "static" angular site, another is a huge java app.

Typically, I use Ctrl + c to stop Jetty, make changes on my angular site, and start Jetty with

```<code>java -jar start.jar -DCommon.properties.path=C:\Jetty
</code>```

If I try to edit the files while Jetty is running, random, buggy code is injected, breaking the site.

So this process is extremely tedious. The java app takes 15-20 seconds to load. So if I forget a slash, it takes about a min to shut it down and restart it.

Is there a way I can just stop/start only one of the webapps instead of all 3 at once?

答:
You seem to be using Windows.

The problems you are having relate to the traditionally wonky FileSystem locking behavior that is unique to Microsoft Windows (no other OS that runs Java does this)

See official documentation about it at
https://www.eclipse.org/jetty/documentation/current/troubleshooting-locked-files-on-windows.html

If you follow the advice laid out in that documentation then you'll not need to stop/start a specific webapp.

Important: Note that the advice in the documentation is for DEVELOPMENT TIME ONLY and is not a good general configuration for production.

Insert from OP:

I followed the directions in the docs above, and it worked! Here's what I did:

Find your webdefault.xml file.

Mine was in C:\Place_where_Jetty_was_installed\Jetty\etc\

Open it and search for UseFileMappedBuffer

Find this:

<init-param>
  <param-name>useFileMappedBuffer</param-name>
  <param-value>true</param-value>
</init-param>

Set param-value to false
  <param-value>false</param-value>

That being said, if you still want to go down this path, there's 2 ways ...

1. Use hotreload

Create an XML deployable for your "reload" webapp and touch it to hot reload just that 1 webapp.

The File: ${jetty.base}/webapps/myapp.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
          "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/myapp</Set>
  <Set name="war"><Property name="jetty.webapps"/>myapp.war</Set>
</Configure>
```

<p>Then to make jetty reload it just ...</p>

```$ touch /path/to/myjettybase/webapps/myapp.xml
```

This standard Posix command will update the timestamp of that file, which will be seen by Jetty as "hey, that file updated, I must reload it"

2. Use JMX to stop/start a specific webapp

Start Jetty with the JMX module active (--module=jmx).

Start a JMX console (the JDK ships with jmc and jconsole) and connect to your running Jetty instance.  Find the MBean for your specific webapp and use the stop() and start() commands on that specific webapp.

Title: How to stop only one app?

Body:
Jetty is running 3 sites from webapps. On of which is a "static" angular site, another is a huge java app.

Typically, I use Ctrl + c to stop Jetty, make changes on my angular site, and start Jetty with

java -jar start.jar -DCommon.properties.path=C:\Jetty

If I try to edit the files while Jetty is running, random, buggy code is injected, breaking the site.

So this process is extremely tedious. The java app takes 15-20 seconds to load. So if I forget a slash, it takes about a min to shut it down and restart it.

Is there a way I can just stop/start only one of the webapps instead of all 3 at once?

Body:
You seem to be using Windows.

The problems you are having relate to the traditionally wonky FileSystem locking behavior that is unique to Microsoft Windows (no other OS that runs Java does this)

See official documentation about it at
https://www.eclipse.org/jetty/documentation/current/troubleshooting-locked-files-on-windows.html

If you follow the advice laid out in that documentation then you'll not need to stop/start a specific webapp.

Important: Note that the advice in the documentation is for DEVELOPMENT TIME ONLY and is not a good general configuration for production.

Insert from OP:

I followed the directions in the docs above, and it worked! Here's what I did:

Find your webdefault.xml file.

Mine was in C:\Place_where_Jetty_was_installed\Jetty\etc\

Open it and search for UseFileMappedBuffer

Find this:

<init-param>
  <param-name>useFileMappedBuffer</param-name>
  <param-value>true</param-value>
</init-param>

Set param-value to false
  <param-value>false</param-value>

That being said, if you still want to go down this path, there's 2 ways ...

1. Use hotreload

Create an XML deployable for your "reload" webapp and touch it to hot reload just that 1 webapp.

The File: ${jetty.base}/webapps/myapp.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN"
          "http://www.eclipse.org/jetty/configure_9_3.dtd">
<Configure class="org.eclipse.jetty.webapp.WebAppContext">
  <Set name="contextPath">/myapp</Set>
  <Set name="war"><Property name="jetty.webapps"/>myapp.war</Set>
</Configure>

Then to make jetty reload it just ...

$ touch /path/to/myjettybase/webapps/myapp.xml

This standard Posix command will update the timestamp of that file, which will be seen by Jetty as "hey, that file updated, I must reload it"

2. Use JMX to stop/start a specific webapp

Start Jetty with the JMX module active (--module=jmx).

Start a JMX console (the JDK ships with jmc and jconsole) and connect to your running Jetty instance.  Find the MBean for your specific webapp and use the stop() and start() commands on that specific webapp.


问:
How to join to two additional collections with conditions
```<code>select tb1.*,tb3 from tb1,tb2,tb3
 where tb1.id=tb2.profile_id and tb2.field='<text>'
 and tb3.user_id = tb2.id and tb3.status =0
</code>```

actually i converted the sql as mongo sql as follows

mongo sql which i used

```<code>db.getCollection('tb1').aggregate
([
  { $lookup:
           { from: 'tb2',
             localField: 'id',
             foreignField: 'profile_id',
             as: 'tb2detail'
            }
   },

   { $lookup:
            { from: 'tb3',
              localField: 'tb2.id',
              foreignField: 'user_id',
              as: 'tb3details'
            }
    },

{ $match:
        { 'status':
                  { '$ne': 'closed'
                  },
          'tb2.profile_type': 'agent',
          'tb3.status': 0
         }
}

])
</code>```

but not getting as per the expected result..

Any help will be appreciated..

答:
What you are missing in here is that $lookup produces an "array" in the output field specified by as in it's arguments. This is the general concept of MongoDB "relations", in that a "relation" between documents is represented as a "sub-property" that is "within" the document itself, being either singular or an "array" for many.

Since MongoDB is "schemaless", the general presumption of $lookup is that you mean "many" and the result is therefore "always" an array. So looking for the "same result as in SQL" then you need to $unwind that array after the $lookup. Whether it's "one" or "many" is of no consequence, since it's still "always" an array:

```<code>db.getCollection.('tb1').aggregate([
  // Filter conditions from the source collection
  { "$match": { "status": { "$ne": "closed" } }},

  // Do the first join
  { "$lookup": {
    "from": "tb2",
    "localField": "id",
    "foreignField": "profileId",
    "as": "tb2"
  }},

  // $unwind the array to denormalize
  { "$unwind": "$tb2" },

  // Then match on the condtion for tb2
  { "$match": { "tb2.profile_type": "agent" } },

  // join the second additional collection
  { "$lookup": {
    "from": "tb3",
    "localField": "tb2.id",
    "foreignField": "id",
    "as": "tb3"
  }},

  // $unwind again to de-normalize
  { "$unwind": "$tb3" },

  // Now filter the condition on tb3
  { "$match": { "tb3.status": 0 } },

  // Project only wanted fields. In this case, exclude "tb2"
  { "$project": { "tb2": 0 } }
])
</code>```

Here you need to note the other things you are missing in the translation:

Sequence is "important"

Aggregation pipelines are more "tersely expressive" than SQL. They are in fact best considered as "a sequence of steps" applied to the datasource in order to collate and transform the data. The best analog to this is "piped" command line instructions, such as:

```<code>ps -ef  | grep mongod | grep -v grep | awk '{ print $1 }'
</code>```

Where the "pipe" | can be considered as a "pipeline stage" in a MongoDB aggregation "pipeline".

As such we want to $match in order to filter things from the "source" collection as our first operation. And this is generally good practice since it removes any documents that did not meet required conditions from further conditions. Just like what is happening in our "command line pipe" example, where we take "input" then "pipe" to a grep to "remove" or "filter".

Paths Matter

Where the very next thing you do here is "join" via $lookup. The result is an "array" of the items from the "from" collection argument matched by the supplied fields to output in the "as" "field path" as an "array".

The naming chosen here is important, since now the "document" from the source collection considers all items from the "join" to now exist at that given path. To make this easy, I use the same "collection" name as the "join" for the new "path".

So starting from the first "join" the output is to "tb2" and that will hold all the results from that collection. There is also an important thing to note with the following sequence of $unwind and then $match, as to how MongoDB actually processes the query.

Certain Sequences "really" matter

Since it "looks like" there are "three" pipeline stages, being $lookup then $unwind and then $match. But in "fact" MongoDB really does something else, which is demonstrated in the output of { "explain": true } added to the .aggregate() command:

```<code>    {
        "$lookup" : {
            "from" : "tb2",
            "as" : "tb2",
            "localField" : "id",
            "foreignField" : "profileId",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "profile_type" : {
                    "$eq" : "agent"
                }
            }
        }
    },
    {
        "$lookup" : {
            "from" : "tb3",
            "as" : "tb3",
            "localField" : "tb2.id",
            "foreignField" : "id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "status" : {
                    "$eq" : 0.0
                }
            }
        }
    },
</code>```

So aside from the first point of "sequence" applying where you need to put the $match statements where they are needed and do the "most good", this actually becomes "really important" with the concept of "joins". The thing to note here is that our sequences of $lookup then $unwind and then $match, actually get processed by MongoDB as just the $lookup stages, with the other operations "rolled up" into the one pipeline stage for each.

This is an important distinction to other ways of "filtering" the results obtained by $lookup. Since in this case, the actual "query" conditions on the "join" from $match are performed on the collection to join "before" the results are returned to the parent.

This in combination with $unwind ( which is translated into unwinding ) as shown above is how MongoDB actually deals with the possibility that the "join" could result in producing an array of content in the source document which causes it to exceed the 16MB BSON limit. This would only happen in cases where the result being joined to is very large, but the same advantage is in where the "filter" is actually applied, being on the target collection "before" results are returned.

It is that kind of handling that best "correlates" to the same behavior as a SQL JOIN. It is also therefore the most effective way to obtain results from a $lookup where there are other conditions to apply to the JOIN aside from simply the "local" of "foreign" key values.

Also note that the other behavior change is is from what is essentially a LEFT JOIN performed by $lookup where the "source" document would always be retained regardless of the presence of a matching document in the "target" collection. Instead the $unwind adds to this by "discarding" any results from the "source" which did not have anything matching from the "target" by the additional conditions in $match.

In fact they are even discarded beforehand due to the implied preserveNullAndEmptyArrays: false which is included and would discard anything where the "local" and "foreign" keys did not even match between the two collections. This is a good thing for this particular type of query as the "join" is intended to the "equal" on those values.

Conclude

As noted before, MongoDB generally treats "relations" a lot differently to how you would use a "Relational Database" or RDBMS. The general concept of "relations" is in fact "embedding" the data, either as a single property or as an array.

You may actually desire such output, which is also part of the reason why that without the $unwind sequence here the output of $lookup is actually an "array". However using $unwind in this context is actually the most effective thing to do, as well as giving a guarantee that the "joined" data does not actually cause the aforementioned BSON limit to be exceed as a result of that "join".

If you actually want arrays of output, then the best thing to do here would be to use the $group pipeline stage, and possibly as multiple stages in order to "normalize" and "undo the results" of $unwind

```<code>  { "$group": {
    "_id": "$_id",
    "tb1_field": { "$first": "$tb1_field" },
    "tb1_another": { "$first": "$tb1_another" },
    "tb3": { "$push": "$tb3" }
  }}
</code>```

Where you would in fact for this case list all the fields you required from "tb1" by their property names using $first to only keep the "first" occurrence ( essentially repeated by results of "tb2" and "tb3" unwound ) and then $push the "detail" from "tb3" into an "array" to represent the relation to "tb1".

But the general form of the aggregation pipeline as given is the exact representation of how results would be obtained from the original SQL, which is "denormalized" output as a result of the "join". Whether you want to "normalize" results again after this is up to you.

Body:
select tb1.*,tb3 from tb1,tb2,tb3
 where tb1.id=tb2.profile_id and tb2.field='<text>'
 and tb3.user_id = tb2.id and tb3.status =0

actually i converted the sql as mongo sql as follows

mongo sql which i used

db.getCollection('tb1').aggregate
([
  { $lookup:
           { from: 'tb2',
             localField: 'id',
             foreignField: 'profile_id',
             as: 'tb2detail'
            }
   },

   { $lookup:
            { from: 'tb3',
              localField: 'tb2.id',
              foreignField: 'user_id',
              as: 'tb3details'
            }
    },

{ $match:
        { 'status':
                  { '$ne': 'closed'
                  },
          'tb2.profile_type': 'agent',
          'tb3.status': 0
         }
}

])

but not getting as per the expected result..

Any help will be appreciated..

Body:
What you are missing in here is that $lookup produces an "array" in the output field specified by as in it's arguments. This is the general concept of MongoDB "relations", in that a "relation" between documents is represented as a "sub-property" that is "within" the document itself, being either singular or an "array" for many.

Since MongoDB is "schemaless", the general presumption of $lookup is that you mean "many" and the result is therefore "always" an array. So looking for the "same result as in SQL" then you need to $unwind that array after the $lookup. Whether it's "one" or "many" is of no consequence, since it's still "always" an array:

db.getCollection.('tb1').aggregate([
  // Filter conditions from the source collection
  { "$match": { "status": { "$ne": "closed" } }},

  // Do the first join
  { "$lookup": {
    "from": "tb2",
    "localField": "id",
    "foreignField": "profileId",
    "as": "tb2"
  }},

  // $unwind the array to denormalize
  { "$unwind": "$tb2" },

  // Then match on the condtion for tb2
  { "$match": { "tb2.profile_type": "agent" } },

  // join the second additional collection
  { "$lookup": {
    "from": "tb3",
    "localField": "tb2.id",
    "foreignField": "id",
    "as": "tb3"
  }},

  // $unwind again to de-normalize
  { "$unwind": "$tb3" },

  // Now filter the condition on tb3
  { "$match": { "tb3.status": 0 } },

  // Project only wanted fields. In this case, exclude "tb2"
  { "$project": { "tb2": 0 } }
])

Here you need to note the other things you are missing in the translation:

Sequence is "important"

Aggregation pipelines are more "tersely expressive" than SQL. They are in fact best considered as "a sequence of steps" applied to the datasource in order to collate and transform the data. The best analog to this is "piped" command line instructions, such as:

ps -ef  | grep mongod | grep -v grep | awk '{ print $1 }'

Where the "pipe" | can be considered as a "pipeline stage" in a MongoDB aggregation "pipeline".

As such we want to $match in order to filter things from the "source" collection as our first operation. And this is generally good practice since it removes any documents that did not meet required conditions from further conditions. Just like what is happening in our "command line pipe" example, where we take "input" then "pipe" to a grep to "remove" or "filter".

Paths Matter

Where the very next thing you do here is "join" via $lookup. The result is an "array" of the items from the "from" collection argument matched by the supplied fields to output in the "as" "field path" as an "array".

The naming chosen here is important, since now the "document" from the source collection considers all items from the "join" to now exist at that given path. To make this easy, I use the same "collection" name as the "join" for the new "path".

So starting from the first "join" the output is to "tb2" and that will hold all the results from that collection. There is also an important thing to note with the following sequence of $unwind and then $match, as to how MongoDB actually processes the query.

Certain Sequences "really" matter

Since it "looks like" there are "three" pipeline stages, being $lookup then $unwind and then $match. But in "fact" MongoDB really does something else, which is demonstrated in the output of { "explain": true } added to the .aggregate() command:

    {
        "$lookup" : {
            "from" : "tb2",
            "as" : "tb2",
            "localField" : "id",
            "foreignField" : "profileId",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "profile_type" : {
                    "$eq" : "agent"
                }
            }
        }
    },
    {
        "$lookup" : {
            "from" : "tb3",
            "as" : "tb3",
            "localField" : "tb2.id",
            "foreignField" : "id",
            "unwinding" : {
                "preserveNullAndEmptyArrays" : false
            },
            "matching" : {
                "status" : {
                    "$eq" : 0.0
                }
            }
        }
    },

So aside from the first point of "sequence" applying where you need to put the $match statements where they are needed and do the "most good", this actually becomes "really important" with the concept of "joins". The thing to note here is that our sequences of $lookup then $unwind and then $match, actually get processed by MongoDB as just the $lookup stages, with the other operations "rolled up" into the one pipeline stage for each.

This is an important distinction to other ways of "filtering" the results obtained by $lookup. Since in this case, the actual "query" conditions on the "join" from $match are performed on the collection to join "before" the results are returned to the parent.

This in combination with $unwind ( which is translated into unwinding ) as shown above is how MongoDB actually deals with the possibility that the "join" could result in producing an array of content in the source document which causes it to exceed the 16MB BSON limit. This would only happen in cases where the result being joined to is very large, but the same advantage is in where the "filter" is actually applied, being on the target collection "before" results are returned.

It is that kind of handling that best "correlates" to the same behavior as a SQL JOIN. It is also therefore the most effective way to obtain results from a $lookup where there are other conditions to apply to the JOIN aside from simply the "local" of "foreign" key values.

Also note that the other behavior change is is from what is essentially a LEFT JOIN performed by $lookup where the "source" document would always be retained regardless of the presence of a matching document in the "target" collection. Instead the $unwind adds to this by "discarding" any results from the "source" which did not have anything matching from the "target" by the additional conditions in $match.

In fact they are even discarded beforehand due to the implied preserveNullAndEmptyArrays: false which is included and would discard anything where the "local" and "foreign" keys did not even match between the two collections. This is a good thing for this particular type of query as the "join" is intended to the "equal" on those values.

Conclude

As noted before, MongoDB generally treats "relations" a lot differently to how you would use a "Relational Database" or RDBMS. The general concept of "relations" is in fact "embedding" the data, either as a single property or as an array.

You may actually desire such output, which is also part of the reason why that without the $unwind sequence here the output of $lookup is actually an "array". However using $unwind in this context is actually the most effective thing to do, as well as giving a guarantee that the "joined" data does not actually cause the aforementioned BSON limit to be exceed as a result of that "join".

If you actually want arrays of output, then the best thing to do here would be to use the $group pipeline stage, and possibly as multiple stages in order to "normalize" and "undo the results" of $unwind

  { "$group": {
    "_id": "$_id",
    "tb1_field": { "$first": "$tb1_field" },
    "tb1_another": { "$first": "$tb1_another" },
    "tb3": { "$push": "$tb3" }
  }}

Where you would in fact for this case list all the fields you required from "tb1" by their property names using $first to only keep the "first" occurrence ( essentially repeated by results of "tb2" and "tb3" unwound ) and then $push the "detail" from "tb3" into an "array" to represent the relation to "tb1".

But the general form of the aggregation pipeline as given is the exact representation of how results would be obtained from the original SQL, which is "denormalized" output as a result of the "join". Whether you want to "normalize" results again after this is up to you.


问:
How do you set up dynamic enumerables on Rails 5?
I'm trying to create a select input that takes specific User models and displays them as a string while saving them as an integer. Typically I would set the enumerable up the same way as below but as a static hash.

While attempting to create a new Product, I keep receiving the following error: "undefined local variable or method `user_business_hash'"

I've tried moving the 'user_business_hash' method to application/products controller, application/products helper with no luck.

Model

```<code>enum user_id: user_business_hash

validates :user_id, inclusion: user_ids.keys

def user_business_hash
# output: {User.business_name => User.id }
# ex: {"Business Name A"=>2, "Business Name B"=>1, "Business Name C"=>5}
array = User.where(account_type: 'Business').map{|x| [x.business_name, x.id] }

hash = array.inject({}) do |memo, (key, value)|
  memo[key] = value
  memo
end

return hash
end
</code>```

Form

```<code><%= form.select :user_id, Product.user_ids.keys, prompt: 'Select', id: :product_user_id %>
</code>```

答:
I think that what you actually want is:

on your controller

```<code>@options = User.where(account_type: 'Business')
</code>```

on your view

```<code>options_from_collection_for_select(@options, "id", "business_name")
</code>```

Body:
I'm trying to create a select input that takes specific User models and displays them as a string while saving them as an integer. Typically I would set the enumerable up the same way as below but as a static hash.

While attempting to create a new Product, I keep receiving the following error: "undefined local variable or method `user_business_hash'"

I've tried moving the 'user_business_hash' method to application/products controller, application/products helper with no luck.

Model

enum user_id: user_business_hash

validates :user_id, inclusion: user_ids.keys

def user_business_hash
# output: {User.business_name => User.id }
# ex: {"Business Name A"=>2, "Business Name B"=>1, "Business Name C"=>5}
array = User.where(account_type: 'Business').map{|x| [x.business_name, x.id] }

hash = array.inject({}) do |memo, (key, value)|
  memo[key] = value
  memo
end

return hash
end

Form

<%= form.select :user_id, Product.user_ids.keys, prompt: 'Select', id: :product_user_id %>

Body:
I think that what you actually want is:

on your controller

@options = User.where(account_type: 'Business')

on your view

options_from_collection_for_select(@options, "id", "business_name")


问:
How to disable attribute menu item after it is clicked?
I can click on the Photos menu 4 times quickly, and the "$.get(..." is sent to the server 4 times.
I need to disable this menu (after it is clicked once) so it can not be clicked on again.
Environment: NodeJS, Express, Pug, Jquery
Thanks,
Pat</p>

```<code>--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos') Photos
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });
</code>```

答:
I normally add a flag for this to clicked element like this

```<code>$('.navigation').on('click',function(){
    if(!$(this).data('clicked')){
         $(this).data('clicked',true);
         // do rest of your staff
    }
});
</code>```

Or if you want to disabled it if its a form element you can use :

```<code>$('.navigation').on('click',function(){
     // do rest of your staff
     $(this).prop( "disabled", true );
});
</code>```

or if you want to block pointer interaction use CSS. pointer-events: none; you can use :

```<code>$('.navigation').on('click',function(){
     // do rest of your staff
     $(this).css( "pointer-events", 'none' );
});
</code>```

Body:
I can click on the Photos menu 4 times quickly, and the "$.get(..." is sent to the server 4 times.
I need to disable this menu (after it is clicked once) so it can not be clicked on again.
Environment: NodeJS, Express, Pug, Jquery
Thanks,
Pat

--------------DOM----------------------------------
// file = photos.pug
div#wrapper2
    div#altnav
      ul
        include includes/altnav.pug
        include includes/navjs.pug
---------------------------------------------------
// file = includes/altnav.pug
li: a.navigation(href='#', data-level='/images/cs/Photos') Photos
---------------------------------------------------
// file = includes/navjs.pug
script.
    $(function(){ // jQuery DOM ready
        $('.navigation').click(function () {
            var level = 'm' + $(this).data('level');        // Append an 'm' so I know this came from navjs.pug
            var url = '/navigation?level=' + escape(level); // Send this to the /router/photos.js
            $.get(url, function (data) {
                $('body').html(data);           // data = new HTML page to be loaded by browser
            });
        });
    });

Body:
I normally add a flag for this to clicked element like this

$('.navigation').on('click',function(){
    if(!$(this).data('clicked')){
         $(this).data('clicked',true);
         // do rest of your staff
    }
});

Or if you want to disabled it if its a form element you can use :

$('.navigation').on('click',function(){
     // do rest of your staff
     $(this).prop( "disabled", true );
});

or if you want to block pointer interaction use CSS. pointer-events: none; you can use :

$('.navigation').on('click',function(){
     // do rest of your staff
     $(this).css( "pointer-events", 'none' );
});


答: ImageMagick is suppose to be real good, but I have no first-hand experience. Mathematica?</p>


问:
Send data from Activity to Fragment already created
I only have found information about how to create a Fragment sending some data to it, but only in its instantiation with the constructor.

But I want to know if it is possible to send some data (for instance, two Double objects) to a Fragment from an Activity without having to create a new instance of the Fragment.

A Fragment that has been previously created.

答:
The easiest way to do this is to define an interface in the Fragment and implement it within the activity. This link should provide a detailed example on how this can be accomplished.
https://developer.android.com/training/basics/fragments/communicating.html

I think the key part you are looking for is here:

```<code>ArticleFragment articleFrag = (ArticleFragment)
      getSupportFragmentManager().findFragmentById(R.id.article_fragment);

if (articleFrag != null) {
    // If article frag is available, we're in two-pane layout...

    // Call a method in the ArticleFragment to update its content
    articleFrag.updateArticleView(position);
} else {
    // Otherwise, we're in the one-pane layout and must swap frags...

    // Create fragment and give it an argument for the selected article
    ArticleFragment newFragment = new ArticleFragment();
    Bundle args = new Bundle();
    args.putInt(ArticleFragment.ARG_POSITION, position);
    newFragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit();
}
</code>```

First try to retrieve the fragment by calling findFragmentById(R.id.fragment_id), and if it is not null you can make a call to the method you defined in your interface to send some data to it.

Body:
The easiest way to do this is to define an interface in the Fragment and implement it within the activity. This link should provide a detailed example on how this can be accomplished.
https://developer.android.com/training/basics/fragments/communicating.html

I think the key part you are looking for is here:

ArticleFragment articleFrag = (ArticleFragment)
      getSupportFragmentManager().findFragmentById(R.id.article_fragment);

if (articleFrag != null) {
    // If article frag is available, we're in two-pane layout...

    // Call a method in the ArticleFragment to update its content
    articleFrag.updateArticleView(position);
} else {
    // Otherwise, we're in the one-pane layout and must swap frags...

    // Create fragment and give it an argument for the selected article
    ArticleFragment newFragment = new ArticleFragment();
    Bundle args = new Bundle();
    args.putInt(ArticleFragment.ARG_POSITION, position);
    newFragment.setArguments(args);

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

    // Replace whatever is in the fragment_container view with this fragment,
    // and add the transaction to the back stack so the user can navigate back
    transaction.replace(R.id.fragment_container, newFragment);
    transaction.addToBackStack(null);

    // Commit the transaction
    transaction.commit();
}

First try to retrieve the fragment by calling findFragmentById(R.id.fragment_id), and if it is not null you can make a call to the method you defined in your interface to send some data to it.


问:
Numbers passed as command line arguments in python not interpreted as integers
I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.

Code:

```<code>import sys

a = sys.argv[1]
b = sys.argv[2]

print a, b

print a+b
</code>```

Input:

```<code>python mySum.py 100 200
</code>```

Output:

```<code>100 200
100200
</code>```

When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.

How can I interpret them as numerics?

答:
Beware of performing comparisons involving command-line arguments, which can lead to really unexpected behavior owing to Python 2's policy for comparing objects of different types ('int' < 'list' < 'string' < 'tuple') as noted here. In Python 3, comparing objects of different types will lead to a TypeError.

For an example of object comparison mayhem, try removing the int() call in section 6.1.1. of the Python tutorial Fibonacci code and you'll get an infinite loop, since the while loop condition becomes: 'int' < 'string'. (This would not happen in Perl, btw).

Great advice from @Jan-Philip above to validate command-line arguments, even for Python 3.

ContentLicense: CC BY-SA 4.0

Body:
I am familiar with C, and have started experimenting in python. My question is regarding the sys.argv command. I've read it is used for a command line interpreter, but when trying to execute a simple program I don't get the results I expect.

Code:

import sys

a = sys.argv[1]
b = sys.argv[2]

print a, b

print a+b

Input:

python mySum.py 100 200

Output:

100 200
100200

When I add the two arguments they are concatenated instead of the two values being added together. It seems that the values are being taken as strings.

How can I interpret them as numerics?


问:
c++ - Why a std::vector<>::const_reference can cast to a non-const pointer?
In g++ , element access operator for const std::vector<> is defined as follows: (/usr/include/c++/7.1.1/bits/stl_vector.h)

```<code>/**
   *  @brief  Subscript access to the data contained in the %vector.
   *  @param __n The index of the element for which data should be
   *  accessed.
   *  @return  Read-only (constant) reference to data.
   *
   *  This operator allows for easy, array-style, data access.
   *  Note that data access with this operator is unchecked and
   *  out_of_range lookups are not defined. (For checked lookups
   *  see at().)
   */
  const_reference
  operator[](size_type __n) const _GLIBCXX_NOEXCEPT
  {
__glibcxx_requires_subscript(__n);
return *(this->_M_impl._M_start + __n);
  }
</code>```

But the following code compiles with no problem using g++ -c const-vector.cpp -Wall -pedantic

```<code>#include <vector>

void sum(const std::vector<int>& data){
  int *ptr;
  ptr = (int*) &data[0];
  if (data.size()>2)
    for (unsigned int i=1;i<data.size();i++)
      ptr[0]+=ptr[i];
return;}
</code>```

So I'm changing the contents of the vector passed by const reference.

According to cppreference.com , operator[] is overloaded:

```<code>reference       operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;
</code>```

In which case compiler will take the second overload?

答:
On a range from "screwriver" to "table saw", the C-style cast is a mortar strike.

When the C-style cast expression is encountered, the compiler attempts to interpret it as the following cast expressions, in this order:

  a) const_cast<new_type>(expression);

  b) static_cast<new_type>(expression), with extensions [...];

  c) static_cast (with extensions) followed by const_cast;

  d) reinterpret_cast<new_type>(expression);

  e) reinterpret_cast followed by const_cast.

It will literally pile up increasingly dangerous casts until the type system bends and/or something breaks. You should use it only when you definitely, absolutely, need to disable every safety you can to perform an operation that goes outside of the normal rules of the language.

In that case, you must know exactly what you're doing, and making a mistake will pretty much always trigger UB without diagnostic (because you just told the compiler to shut up and trust you).

Forcefully modifying an unknown const object is not a good idea -- unless you can prove it has originally been declared as non-const, you're off to UB-land.

Body:
In g++ , element access operator for const std::vector<> is defined as follows: (/usr/include/c++/7.1.1/bits/stl_vector.h)

/**
   *  @brief  Subscript access to the data contained in the %vector.
   *  @param __n The index of the element for which data should be
   *  accessed.
   *  @return  Read-only (constant) reference to data.
   *
   *  This operator allows for easy, array-style, data access.
   *  Note that data access with this operator is unchecked and
   *  out_of_range lookups are not defined. (For checked lookups
   *  see at().)
   */
  const_reference
  operator[](size_type __n) const _GLIBCXX_NOEXCEPT
  {
__glibcxx_requires_subscript(__n);
return *(this->_M_impl._M_start + __n);
  }

But the following code compiles with no problem using g++ -c const-vector.cpp -Wall -pedantic

#include <vector>

void sum(const std::vector<int>& data){
  int *ptr;
  ptr = (int*) &data[0];
  if (data.size()>2)
    for (unsigned int i=1;i<data.size();i++)
      ptr[0]+=ptr[i];
return;}

So I'm changing the contents of the vector passed by const reference.

According to cppreference.com , operator[] is overloaded:

reference       operator[]( size_type pos );
const_reference operator[]( size_type pos ) const;

In which case compiler will take the second overload?


问:
Translating decryption function from Python to C#
I am translating a decryption function that I have found on the internet. The function is written in Python, and I am translating it to C#. I have a fair amount of it done (hopefully correctly), but some of the syntax I'm having a hard time reading.

Here's the original function:

```<code>def decrypt_signature(s):
arr = list(s)
   arr[0], arr[52] = arr[52%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr[0], arr[21] = arr[21%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr.reverse()

   return "".join(arr)
</code>```

And here's what I have translated so far:

```<code>private string DecryptSig(string s)
        {
            //arr = list(s)
            char[] arr = s.ToArray();

            //arr[0], arr[52] = arr[52%len(arr)], arr[0]
            var temp = arr[0];
            arr[0] = arr[52 % arr.Length];
            arr[52 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //?????????????????

            //arr[0], arr[21] = arr[21 % len(arr)], arr[0]
            temp = arr[0];
            arr[0] = arr[21 % arr.Length];
            arr[21 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //??????????????????

            //arr.reverse()
            arr.Reverse();

            //return "".join(arr)
            return "" + new string(arr);
        }
</code>```

What does the author do when they write arr = arr[3:]? To me it appears like it's just taking the first three values of the array and writing them back to their original indices.

答:
in Python, you can get some elements from a list using [startingIndex:EndingIndex]

arr[:] means all the elements

arr[3:] means skip 3 and take the rest

As Uriel mentions, the C# equivalent is Skip(count)

arr = arr.Skip(3).ToArray();

and you need to add this:

using System.Linq;

Python Slices: Explain slice notation

Body:
I am translating a decryption function that I have found on the internet. The function is written in Python, and I am translating it to C#. I have a fair amount of it done (hopefully correctly), but some of the syntax I'm having a hard time reading.

Here's the original function:

def decrypt_signature(s):
arr = list(s)
   arr[0], arr[52] = arr[52%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr[0], arr[21] = arr[21%len(arr)], arr[0]
   arr.reverse()
   arr = arr[3:]
   arr.reverse()

   return "".join(arr)

And here's what I have translated so far:

private string DecryptSig(string s)
        {
            //arr = list(s)
            char[] arr = s.ToArray();

            //arr[0], arr[52] = arr[52%len(arr)], arr[0]
            var temp = arr[0];
            arr[0] = arr[52 % arr.Length];
            arr[52 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //?????????????????

            //arr[0], arr[21] = arr[21 % len(arr)], arr[0]
            temp = arr[0];
            arr[0] = arr[21 % arr.Length];
            arr[21 % arr.Length] = temp;

            //arr.reverse()
            arr.Reverse();

            //arr = arr[3:]
            //??????????????????

            //arr.reverse()
            arr.Reverse();

            //return "".join(arr)
            return "" + new string(arr);
        }

What does the author do when they write arr = arr[3:]? To me it appears like it's just taking the first three values of the array and writing them back to their original indices.


问:
Decompile jar file to use it as a project in intellij
I have a jar file but not source code. I had some issue with this code which is not working as expected. So I want to decompile it use it as a project in intellij. Could you please let me know how can I do that?</p>

答: use jd-gui and copy the source code in intellij. also normally with decomiplation your code will have multiple localobject and you have to deal with it</p>


问:
Google Drive API Client (Python): retrieve permissions
I got this error about with Google Drive API example.Can you help me ?
I used an old Google project (that use Blogger API - work well) by add new Enable API for Google Drive into Google project.
I make a new python file and I try to deal with Google Drive API.
I used same json credentials.

My source code: https://paste.fedoraproject.org/paste/xTH1zf3tEtLH5~zvuAHf8Q

```<code>def retrieve_permissions(service, file_id):
  """Retrieve a list of permissions.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to retrieve permissions for.
  Returns:
    List of permissions.
  """
  try:
    permissions = service.permissions().list(fileId=file_id).execute()
    return permissions.get('items', [])
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None
</code>```

the main function:

```<code>if __name__ == '__main__':
    served = get_service()
    print "-------"
    print retrieve_permissions(served,'client_secret_driv.json')
    print "======="
</code>```

The error is

```<code>C:\Python27\python.exe C:/Python27/goo_drive_002.py
-------
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/client_secret_driv.json/permissions?alt=json returned "Insufficient Permission">
None
=======

Process finished with exit code 0
</code>```

答:
Modification points :

In order to retrieve the permissions of file, the file ID is required. In your script, filename is given for fileID of service.permissions().list(fileId=file_id).execute(). So an error occurs. For this, it retrieves file ID from file name Using service.files().list().

When you want the permission data from response, please change from permissions.get('items', []) to permissions.get('permissions', [])

Modified script :

```<code>file_name = 'client_secret_driv.json'
file_id = service.files().list(q="name='" + file_name + "' and trashed=false", fields="files(id)").execute()
permissions = service.permissions().list(fileId=file_id["files"][0]["id"]).execute()
result = permissions.get('permissions', [])
</code>```

If I misunderstand your question, I'm sorry.

Body:
I got this error about with Google Drive API example.Can you help me ?
I used an old Google project (that use Blogger API - work well) by add new Enable API for Google Drive into Google project.
I make a new python file and I try to deal with Google Drive API.
I used same json credentials.

My source code: https://paste.fedoraproject.org/paste/xTH1zf3tEtLH5~zvuAHf8Q

def retrieve_permissions(service, file_id):
  """Retrieve a list of permissions.

  Args:
    service: Drive API service instance.
    file_id: ID of the file to retrieve permissions for.
  Returns:
    List of permissions.
  """
  try:
    permissions = service.permissions().list(fileId=file_id).execute()
    return permissions.get('items', [])
  except errors.HttpError, error:
    print 'An error occurred: %s' % error
  return None

the main function:

if __name__ == '__main__':
    served = get_service()
    print "-------"
    print retrieve_permissions(served,'client_secret_driv.json')
    print "======="

The error is

C:\Python27\python.exe C:/Python27/goo_drive_002.py
-------
An error occurred: <HttpError 403 when requesting https://www.googleapis.com/drive/v3/files/client_secret_driv.json/permissions?alt=json returned "Insufficient Permission">
None
=======

Process finished with exit code 0

Body:
Modification points :

In order to retrieve the permissions of file, the file ID is required. In your script, filename is given for fileID of service.permissions().list(fileId=file_id).execute(). So an error occurs. For this, it retrieves file ID from file name Using service.files().list().

When you want the permission data from response, please change from permissions.get('items', []) to permissions.get('permissions', [])

Modified script :

file_name = 'client_secret_driv.json'
file_id = service.files().list(q="name='" + file_name + "' and trashed=false", fields="files(id)").execute()
permissions = service.permissions().list(fileId=file_id["files"][0]["id"]).execute()
result = permissions.get('permissions', [])

If I misunderstand your question, I'm sorry.


问:
Split text file into smaller multiple text file using command line
I have multiple text file with about 100,000 lines and I want to split them into smaller text files of 5000 lines each.

I used:

```<code>split -l 5000 filename.txt
</code>```

That creates files:

```<code>xaa
xab
aac
xad
xbe
aaf
</code>```

files with no extensions. I just want to call them something like:

```<code>file01.txt
file02.txt
file03.txt
file04.txt
</code>```

or if that is not possible, i just want them to have the ".txt" extension.

答:
here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.</p>

```<code>var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();
</code>```

Body:
I have multiple text file with about 100,000 lines and I want to split them into smaller text files of 5000 lines each.

I used:

split -l 5000 filename.txt

That creates files:

xaa
xab
aac
xad
xbe
aaf

files with no extensions. I just want to call them something like:

file01.txt
file02.txt
file03.txt
file04.txt

or if that is not possible, i just want them to have the ".txt" extension.

Body:
here is one in c# that doesn't run out of memory when splitting into large chunks! I needed to split 95M file into 10M x line files.

var fileSuffix = 0;
int lines = 0;
Stream fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
StreamWriter sw = new StreamWriter(fstream);

using (var file = File.OpenRead(filename))
using (var reader = new StreamReader(file))
{
    while (!reader.EndOfStream)
    {
        sw.WriteLine(reader.ReadLine());
        lines++;

        if (lines >= 10000000)
        {
              sw.Close();
              fstream.Close();
              lines = 0;
              fstream = File.OpenWrite($"{filename}.{(++fileSuffix)}");
              sw = new StreamWriter(fstream);
        }
    }
}

sw.Close();
fstream.Close();